Reputation: 455
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
Upvotes: 1
Views: 2157
Reputation: 109546
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]
Upvotes: 2
Reputation: 22954
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
Upvotes: 0
Reputation: 23223
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)
Upvotes: 0