【问题标题】:Comparing some data of a file with another file in python将文件的某些数据与python中的另一个文件进行比较
【发布时间】:2012-08-13 08:14:11
【问题描述】:

我确实有一个文件 f1,其中包含一些文本,可以说“一切都很好”。 在另一个文件 f2 中,我可能有 100 行,其中一条是“一切都很好”。

现在我想看看文件 f2 是否包含文件 f1 的内容。

如果有人提出解决方案,我将不胜感激。

谢谢

【问题讨论】:

  • 提供你到目前为止的代码并解释你的问题是什么?我们不为你做作业。

标签: python file file-comparison


【解决方案1】:
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'

【讨论】:

  • 能否请您对我的问题给予正面评价,我将不胜感激:),问题可以在这里找到stackoverflow.com/questions/12138298/…
  • Sara 发现,这只适用于 Python 2.7;在 Python 2.6 中,您必须嵌套 with 语句,因为尚不支持在一行中使用多个上下文管理器。
【解决方案2】:
template = file('your_name').read()

for i in file('2_filename'):
    if template in i:
       print 'found'
       break

【讨论】:

  • 如果行应该完全一样,你可以使用模板 == i
  • 只是一个文体评论:使用i 代替integers。这里sl 可能更适合。
【解决方案3】:
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',则使用其他方法将不起作用。

【讨论】:

    【解决方案4】:
    fileOne = f1.readlines()
    fileTwo = f2.readlines()
    

    现在fileOnefileTwo 是文件中的行列表,现在只需检查

    if set(fileOne) <= set(fileTwo):
        print "file1 is in file2"
    

    【讨论】:

      猜你喜欢
      • 2015-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-08
      • 2018-08-22
      • 1970-01-01
      相关资源
      最近更新 更多