我想在另一个文本文件中找到list.txt中列出的字符串(每行一个字符串),以防我发现它打印'string,one_sentence'以防万一找不到'string,another_sentence'。我正在使用以下代码,但它只是在文件list.txt的字符串列表中找到最后一个字符串。无法理解可能是什么原因?
data = open('c:/tmp/textfile.TXT').read()
for x in open('c:/tmp/list.txt').readlines():
if x in data:
print(x,',one_sentence')
else:
print(x,',another_sentence')
答案 0 :(得分:5)
当您使用readlines()
读取文件时,生成的列表元素确实具有尾随换行符。可能,这就是为什么你的匹配次数少于预期的原因。
而不是写
for x in list:
写
for x in (s.strip() for s in list):
这将从list
中的字符串中删除前导和尾随空格。因此,它从字符串中删除尾随的换行符。
为了整合你的程序,你可以这样做:
with open('c:/tmp/textfile.TXT') as f:
haystack = f.read()
if not haystack:
sys.exit("Could not read haystack data :-(")
with open('c:/tmp/list.txt') as f:
for needle in (line.strip() for line in f):
if needle in haystack:
print(needle, ',one_sentence')
else:
print(needle, ',another_sentence')
我不想做太剧烈的改变。最重要的区别是我通过with
语句在这里使用了上下文管理器。它确保为您正确处理文件(主要是关闭)。此外,使用生成器表达式即时剥离“针”线。上述方法逐行读取和处理针文件,而不是立即将整个文件加载到内存中。当然,这只会对大文件产生影响。
答案 1 :(得分:0)
readlines()在从列表文件中读取的每个字符串的末尾保留换行符。在这些字符串上调用strip()来删除那些(和其他所有空格)字符。