【发布时间】:2012-08-13 08:14:11
【问题描述】:
我确实有一个文件 f1,其中包含一些文本,可以说“一切都很好”。 在另一个文件 f2 中,我可能有 100 行,其中一条是“一切都很好”。
现在我想看看文件 f2 是否包含文件 f1 的内容。
如果有人提出解决方案,我将不胜感激。
谢谢
【问题讨论】:
-
提供你到目前为止的代码并解释你的问题是什么?我们不为你做作业。
标签: python file file-comparison
我确实有一个文件 f1,其中包含一些文本,可以说“一切都很好”。 在另一个文件 f2 中,我可能有 100 行,其中一条是“一切都很好”。
现在我想看看文件 f2 是否包含文件 f1 的内容。
如果有人提出解决方案,我将不胜感激。
谢谢
【问题讨论】:
标签: python file file-comparison
with open("f1") as f1,open("f2") as f2:
if f1.read().strip() in f2.read():
print 'found'
编辑: 由于 python 2.6 不支持单行多个上下文管理器:
with open("f1") as f1:
with open("f2") as f2:
if f1.read().strip() in f2.read():
print 'found'
【讨论】:
with 语句,因为尚不支持在一行中使用多个上下文管理器。
template = file('your_name').read()
for i in file('2_filename'):
if template in i:
print 'found'
break
【讨论】:
i 代替integers。这里s 或l 可能更适合。
with open(r'path1','r') as f1, open(r'path2','r') as f2:
t1 = f1.read()
t2 = f2.read()
if t1 in t2:
print "found"
如果您要搜索的字符串中有'\n',则使用其他方法将不起作用。
【讨论】:
fileOne = f1.readlines()
fileTwo = f2.readlines()
现在fileOne 和fileTwo 是文件中的行列表,现在只需检查
if set(fileOne) <= set(fileTwo):
print "file1 is in file2"
【讨论】: