如何比较两个txt文件以确定它们是否相同?

我正在试着写一个程序,比较两个txt文件,看看它们是否相同。该程序将提示用户输入两个txt文件,然后进行比较。如果它们相同,它应该打印yes,如果不相同,它应该打印no,后跟每个不同文件的第一行。我知道如何提示用户输入文件名,但我不知道如何比较它们。

# 回答1


对于小文件,两者都可以作为字符串读取到内存中,并进行相等比较,如下所示:

选择 | 换行 | 行号
  1. >>> s1 = "abcdef"
  2. >>> s2 = "abcdef"
  3. >>> s1 == s2
  4. True
  5. >>> s3 = "xyz"
  6. >>> s1 == s3
  7. False
  8. >>> 

或者,您可以使用模块
文件管理
以比较文件。

# 回答2


我已经把它们进口了,然后再把它们组合起来!我该怎么做?
# 回答3

选择 | 换行 | 行号
  1. s1 = open(file_name1).read()
  2. s2 = open(file_name2).read()
  3. if s1 == s2:
  4.     print "File contents are identical"
  5. else:
  6.     print "File contents are different"
# 回答4


我其实是一个人走了那么远,不过还是要谢谢你。你能帮我弄清楚如何让它打印每个文件中不同的第一行吗?
# 回答5


打开该文件的方式与您所拥有的相同:
Infile=OPEN("文件名","r")
# 回答6


这就是我有的,但它不能正常运行。

选择 | 换行 | 行号
  1. file1 = raw_input("What is the name of the first sile including the .txt?")
  2. file2 = raw_input("what is the name of the second file including the .txt?")
  3.  
  4. file1 = open("file1" , "r")
  5. file2 = open("file2", "r")
  6.  
  7. if file1 == file2:
  8.     print("Yes")
  9. else:
  10.     print("No")
  11.  
# 回答7


要使用for()循环打开和读取文件,请阅读第9.1节
这里

# 回答8


在我的方法中,它在第4行显示没有这样的文件或目录。我如何修复它?
# 回答9

选择 | 换行 | 行号
  1. fn1 = raw_input("Enter file name.")
  2. fileobj1 = open(fn1, 'r')

文件名是文本字符串,并被分配给该标识符
Fn1
。内置函数返回打开的文件对象
打开()
并将其分配给标识符
文件对象1
。请注意该标识符
Fn1
表示文件名的参数。

# 回答10


我试过了,仍然显示没有这样的文件或目录
# 回答11


这就是我所拥有的:

选择 | 换行 | 行号
  1. fn1 = raw_input("What is the name of the first file (be sure to include .txt after the filename)?")
  2. fn2 = raw_input("What is the name of the second file (be sure to include .txt after the filename)?")
  3. fileobj1 = open("fn1", "r")
  4. fileobj2 = open("fn2", "r")
  5. if file1 == file2:
  6.     print ("Yes these files are the same.")
  7. else:
  8.     print("No these file are not the same.")
  9.  
# 回答12


除非文件位于PYTHONPATH中,否则必须提供文件的完整路径,请参见
这里

选择 | 换行 | 行号
  1. import sys
  2. print sys.path
  3. ##
  4. ## if the path to the file is not in the above then you have to provide the path
  5. fileobj1 = open("/path/to/fn1", "r")
  6. ##
  7. ## or add it to sys.path
  8. sys.path.append("/path/to")
  9. fileobj1 = open("fn1", "r") 

标签: python

添加新评论