I am new at Python and need some help.
I have a file with x number of lines. I want to compare each line of that file with another line, and write that line to that file if they are different.
I looked for an answer but didn't find anything that I can use. I tried something myself but it doesn't work.
My code:
filename = ...
my_file = open(filename, 'r+')
for line in my_file:
new_line = ("text")
print line
print new_line
if new_line == line:
print('same')
else:
print('diffrent')
my_file.write('%s' % (new_line))
I only want my application to write the line to the file if it doesn't already exist there.
contents of filename
====================
text
text1
text2
In the case above where new line is "text", the application shouldn't do anything because that line already exist in the file. However, if the new line is "text3" then it should be written to the file as follows:
contents of filename
====================
text
text1
text2
text3
First, let's read the contents of the file so that we can check if the new line is already in there.
existing_lines = [line.rstrip('\n') for line in open(filename, 'r')]
Let's say you have a separate list named new_lines that contains all lines you'd like to check against the file. You can then check to see which ones are new as follows:
new = [line for line in new_lines if line not in existing_lines]
These are the lines that you'd then like to append to your existing file:
with open(filename, 'a') as f:
[f.write(line + '\n') for line in new]
with open('1.txt') as f1, open('2.txt') as f2, open('diff.txt','w') as dst:
while True:
l1 = f1.readline()
l2 = f2.readline()
if not l1 and not l2:
break
if l1 != l2:
dst.write(l1)
I would rather suggest you to create a new file and write the difference to the new file instead of editing the file2.txt
with open("file1.txt", "r") as first_file, open("file2.txt", "r") as second_file:
file1 = first_file.readlines()
file2 = second_file.readlines()
length = min(len(file1), len(file2))
for i in xrange(length):
if file1[i].strip() != file2[i].strip():
#Do something here
Related
I have copied a certain part of a .txt file into a list. I need to go to particular line and paste/append it.
file = open(filepath, 'r')
with open(filepath) as f: # SEARCH IF STAGE1 & STAGE2 EXIST OR NOT
if 'stage1' in f.read():
print("stage 1")
data = file.readlines()[11:26]
print(*data, sep='')
with open(filepath) as f:
srno = f.readlines()[7:8]
print(*srno, sep='')
Now that I've copied lines 11-26 and line 7-8.. I want to paste/append it in the text file above line 5. How would I go about doing that?
I've written this but it only appends it to the end of the text file.
with open(filepath, 'a+') as fa:
fa.writelines(srno)
fa.writelines("M0\n\n")
for i in data:
fa.writelines(i)
file.close()
I want to write what I've copied in 'data' and 'srno' to line 5 in the text file.
I would like to read a file line by line but ignore any that contain a colon (:).
I'm currently opening one file, reading it, and trying to print it before eventually put it into a new file.
def shoppinglist():
infile = open('filename.txt')
contents = infile.readline()
output = open('outputfilename.txt', 'w')
while ":" not in contents:
contents = infile.readline()
else:
contentstr = contents.split()
print(contentstr)
output.write(contents)
infile.close()
output.close()
As it is, one line is repeated over and over and over.
Try:
def shoppinglist():
contents = ""
with open('filename.txt', 'r') as infile:
for line in infile.readlines():
if ":" not in line:
contents += line
with open('outputfilename.txt', 'w') as output_file:
output_file.write(contents)
I would like to check for a string "rele" in a python text file and if string is not present then copy the last line of the file and then modify it as below to add as a new entry.
Example:
Actual File: Where "rele" is not present
"123456",1,0,"mher",0,"N",01Jan1986 00:00,130:00,
"123456",1,1,"ermt",0,"N",01Jan1986 00:00,100:00,
"123456",1,2,"irbt",0,"N",01Jan1986 00:00,120:00,
Expected Output:
"123456",1,0,"mher",0,"N",01Jan1986 00:00,130:00,
"123456",1,1,"ermt",0,"N",01Jan1986 00:00,0:00,
"123456",1,2,"irbt",0,"N",01Jan1986 00:00,0:00,
"123456",1,3,"rele",0,"0000",01Jan1986 00:00,0:00,
Last entry of the file is similar to its previous except few changes to it's 3,4 and 6 columns.
My code:
fp = open(srcEtab.txt, 'w')
for line in lines:
if 'rele' in line:
foundRelOrPickup = True
if not foundRelOrPickup:
fp1 = open ( 'srcEtab.txt',"w" )
lineList = fp1.readlines()
new_line = lineList[len(lineList)-1]
fp1.write(new_line)
fp.close()
fp1.close()
with open(yourFile) as f:
lines = f.readlines()
if not any(map(lambda line: "rele" in line,lines)):
last_line_words = lines[-1].split(',')
last_line_words[2] = len(lines)
last_line_words[3] = '"rele"'
last_line_words[5] = '"0000"'
lines.append(",".join([str(i) for i in last_line_words]))
with open(otherFile, "w") as f1:
for line in lines:
f1.write(line)
imp,2,6,7
ads,4,5,6
sfd,2,5,8
I have a text file that looks like this
I want to delete the line that has imp in it.
All the other methods I have seen to delete lines from files only work for single strings
Following this question link, you can try this:
fn = 'Test.txt'
f = open(fn)
output = []
for line in f:
if not "imp" in line:
output.append(line)
f.close()
f = open(fn, 'w')
f.writelines(output)
f.close()
Result:
ads,4,5,6
sfd,2,5,8
I am very new to programming and the python language.
I know how to open a file in python, but the question is how can I open the file as a parameter of a function?
example:
function(parameter)
Here is how I have written out the code:
def function(file):
with open('file.txt', 'r') as f:
contents = f.readlines()
lines = []
for line in f:
lines.append(line)
print(contents)
You can easily pass the file object.
with open('file.txt', 'r') as f: #open the file
contents = function(f) #put the lines to a variable.
and in your function, return the list of lines
def function(file):
lines = []
for line in f:
lines.append(line)
return lines
Another trick, python file objects actually have a method to read the lines of the file. Like this:
with open('file.txt', 'r') as f: #open the file
contents = f.readlines() #put the lines to a variable (list).
With the second method, readlines is like your function. You don't have to call it again.
Update
Here is how you should write your code:
First method:
def function(file):
lines = []
for line in f:
lines.append(line)
return lines
with open('file.txt', 'r') as f: #open the file
contents = function(f) #put the lines to a variable (list).
print(contents)
Second one:
with open('file.txt', 'r') as f: #open the file
contents = f.readlines() #put the lines to a variable (list).
print(contents)
Hope this helps!
Python allows to put multiple open() statements in a single with. You comma-separate them. Your code would then be:
def filter(txt, oldfile, newfile):
'''\
Read a list of names from a file line by line into an output file.
If a line begins with a particular name, insert a string of text
after the name before appending the line to the output file.
'''
with open(newfile, 'w') as outfile, open(oldfile, 'r', encoding='utf-8') as infile:
for line in infile:
if line.startswith(txt):
line = line[0:len(txt)] + ' - Truly a great person!\n'
outfile.write(line)
# input the name you want to check against
text = input('Please enter the name of a great person: ')
letsgo = filter(text,'Spanish', 'Spanish2')
And no, you don't gain anything by putting an explicit return at the end of your function. You can use return to exit early, but you had it at the end, and the function will exit without it. (Of course with functions that return a value, you use the return to specify the value to return.)
def fun(file):
contents = None
with open(file, 'r') as fp:
contents = fp.readlines()
## if you want to eliminate all blank lines uncomment the next line
#contents = [line for line in ''.join(contents).splitlines() if line]
return contents
print fun('test_file.txt')
or you can even modify this, such a way it takes file object as a function arguement as well
Here's a much simpler way of opening a file without defining your own function in Python 3.4:
var=open("A_blank_text_document_you_created","type_of_file")
var.write("what you want to write")
print (var.read()) #this outputs the file contents
var.close() #closing the file
Here are the types of files:
"r": just to read a file
"w": just to write a file
"r+": a special type which allows both reading and writing of the file
For more information see this cheatsheet.
def main():
file=open("chirag.txt","r")
for n in file:
print (n.strip("t"))
file.close()
if __name__== "__main__":
main()
the other method is
with open("chirag.txt","r") as f:
for n in f:
print(n)