如何比较Python中文件的内容?

2024-04-26 00:35:26 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的代码,到目前为止,我试图比较用户提供的文件,如果两个文件中的内容是相同的打印。如果它是相同的字符串内容,我想打印Yes如果不是,打印No以及两个文件中的单词。你知道吗

print ('Enter the first file name: ', end = '')
FIRST_FILE = input()

print ('Enter the second file name: ', end = '')
SECOND_FILE = input()

if SECOND_FILE == line in FIRST_FILE:
    print('Yes')
else:
    print('No')

infile = open('one.txt', 'w')
infile.write('Hello') 
infile.close() 

infile2 = open('SameAsone.txt', 'w')
infile2.write('Hello') 
infile2.close()

infile3 = open('DifferentFromone.txt', 'w')
infile3.write('Bye') 
infile3.close() 

谢谢。你知道吗


Tags: 文件thenotxt内容closeopeninfile
3条回答

一个简单的方法是使用filecmp

import filecmp
check = filecmp.cmp('file1.txt', 'file1.txt')
print ('No', 'Yes')[check]

如果您想了解更多信息,请参阅docs

您可以使用.read,我建议使用with语句,因为不需要手动关闭文件。你知道吗

def compare_files(fn1, fn2)
    with open(fn1, 'r') as file1, open(fn2, 'r') as file2:
            return file1.read() == file2.read()


first_file = input('Enter the first file name: ')
second_file = input('Enter the second file name: ')

print(['No', 'Yes']compare_files(first_file, second_file))

一种简单的方法是使用f.read()读取两个文件,其中f是以读取('r')模式打开的文件。read()操作返回文件的字符串内容。你知道吗

然后,我们使用==比较文件的读取内容,以确定字符串序列是否相同。你知道吗

fileAfileB成为存在的文件名,因此,最小的文件比较代码应该是:

  f = open(fileA, 'r')
  contentA = f.read()
  f.close()
  f = open(fileB, 'r')
  contentB = f.read()
  f.close()

  result = "No"
  if contentA == contentB:
    result = "Yes"

您还应该处理其中一个文件不存在的情况(如果fileA, fileB中的任何一个引用了不存在的文件,则最小代码将返回一个回溯)。你知道吗

相关问题 更多 >

    热门问题