[英]How to compare all lines in some file with another line?
I am new at Python and need some help. 我是Python新手,需要一些帮助。
I have a file with x
number of lines. 我有一个带有x
行数的文件。 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: 但是,如果新行是“ text3”,则应按以下方式将其写入文件:
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. 假设您有一个名为new_lines
的单独列表,其中包含您要对照该文件检查的所有行。 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]
I would rather suggest you to create a new file and write the difference to the new file instead of editing the file2.txt
我宁愿建议您创建一个新文件并将差异写入新文件,而不是编辑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
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.