2017-04-27 100 views
1

我正在尝试做一个函数来比较两个txt文件。如果它识别出在一个文件中但不在另一个文件中的新行,则它会将它们添加到list中,并且也将该文件添加到不包含这些新行的文件中。它没有这样做。这是我的功能。我究竟做错了什么?检查一个txt文件中是否有新字符串

newLinks = [] 

def newer(): 
with open('cnbcNewLinks.txt', 'w') as newL: 
    for line in open('cnbcCleanedLinks.txt'): 
     if line not in "cnbcNewLinks.txt": 
      newLinks.append(line) 
      newL.write(line) 
     else: 
      continue 
cleaned = ''.join(newLinks) 
print(cleaned) 
+2

'if line not in“cnbcNewLinks.txt”:'只是测试文件名的文本字符串,它是* not *搜索文件。 – cdarke

+0

那么我如何搜索新字符串? –

+0

使用文件句柄'newL',就像您在写入文件时所做的那样。 –

回答

1

我把@Alex建议的python代码。

请参阅文档set

我用a.txtb.txt替换你的文本文件名,以便易读。

# First read the files and compare then using `set` 
with open('a.txt', 'r') as newL, open('b.txt', 'r') as cleanL: 
    a = set(newL) 
    b = set(cleanL) 
    add_to_cleanL = list(a - b) # list with line in newL that are not in cleanL 
    add_to_newL = list(b - a) # list with line in cleanL that are not in newL 

# Then open in append mode to add at the end of the file 
with open('a.txt', 'a') as newL, open('b.txt', 'a') as cleanL: 
    newL.write(''.join(add_to_newL)) # append the list at the end of newL 
    cleanL.write(''.join(add_to_cleanL)) # append the list at the end of cleanL 
1

如果文件不是很大,那么移动在列表数据, 两个列表的转换中设置和使用“不同”内置函数,两次。 然后在文件中添加差异。

-1

这里有一个工作

newLinks = [] 

with open('cnbcNewLinks.txt', 'a+') as newL: 
    new_file_lines = newL.read().splitlines() 
    with open('cnbcCleanedLinks.txt') as cleanL: 
     clean_file_lines = cleanL.read().splitlines() 
    for line in clean_file_lines: 
     if line not in new_file_lines: 
      newLinks.append(line) 
      line_to_append = '\n'+line 
      newL.write(line_to_append) 

cleaned = ''.join(newLinks) 
print(cleaned) 

由于@cdarke评论的代码,你没有遍历文件内容,而是将文件名字符串。

此外,使用for line in open('filename')是不好的做法。 改为使用'with'语句

newL.read().splitlines()整齐地将您的文件内容转换为每个元素为一行的列表。

+0

'a + '模式允许我们同时追加和读取文件。 – Shiva

+0

它不起作用。它只是在第二次运行中添加相同的链接,并且它总是打印相同的文件,所以实际上它只是查看从Cl​​eanedLinks中获取哪些文件,并在每次运行后一遍又一遍地读取它们。 –

+0

假设,cnbcNewLinks.txt包含 line1,line2 和cnbcCleanedLInks包含 line3。 运行上面的代码仅将第3行附加到第一个文件。 – Shiva

相关问题