如何比较两个txt文件以确定它们是否相同?
我正在试着写一个程序,比较两个txt文件,看看它们是否相同。该程序将提示用户输入两个txt文件,然后进行比较。如果它们相同,它应该打印yes,如果不相同,它应该打印no,后跟每个不同文件的第一行。我知道如何提示用户输入文件名,但我不知道如何比较它们。
# 回答1
对于小文件,两者都可以作为字符串读取到内存中,并进行相等比较,如下所示:
对于小文件,两者都可以作为字符串读取到内存中,并进行相等比较,如下所示:
选择 | 换行 | 行号
- >>> s1 = "abcdef"
- >>> s2 = "abcdef"
- >>> s1 == s2
- True
- >>> s3 = "xyz"
- >>> s1 == s3
- False
- >>>
或者,您可以使用模块
文件管理
以比较文件。
# 回答2
我已经把它们进口了,然后再把它们组合起来!我该怎么做?
我已经把它们进口了,然后再把它们组合起来!我该怎么做?
# 回答3
选择 | 换行 | 行号
- s1 = open(file_name1).read()
- s2 = open(file_name2).read()
- if s1 == s2:
- print "File contents are identical"
- else:
- print "File contents are different"
# 回答4
我其实是一个人走了那么远,不过还是要谢谢你。你能帮我弄清楚如何让它打印每个文件中不同的第一行吗?
我其实是一个人走了那么远,不过还是要谢谢你。你能帮我弄清楚如何让它打印每个文件中不同的第一行吗?
# 回答5
打开该文件的方式与您所拥有的相同:
Infile=OPEN("文件名","r")
打开该文件的方式与您所拥有的相同:
Infile=OPEN("文件名","r")
# 回答6
这就是我有的,但它不能正常运行。
这就是我有的,但它不能正常运行。
选择 | 换行 | 行号
- file1 = raw_input("What is the name of the first sile including the .txt?")
- file2 = raw_input("what is the name of the second file including the .txt?")
- file1 = open("file1" , "r")
- file2 = open("file2", "r")
- if file1 == file2:
- print("Yes")
- else:
- print("No")
# 回答7
要使用for()循环打开和读取文件,请阅读第9.1节
这里
。
要使用for()循环打开和读取文件,请阅读第9.1节
这里
。
# 回答8
在我的方法中,它在第4行显示没有这样的文件或目录。我如何修复它?
在我的方法中,它在第4行显示没有这样的文件或目录。我如何修复它?
# 回答9
选择 | 换行 | 行号
- fn1 = raw_input("Enter file name.")
- fileobj1 = open(fn1, 'r')
文件名是文本字符串,并被分配给该标识符
Fn1
。内置函数返回打开的文件对象
打开()
并将其分配给标识符
文件对象1
。请注意该标识符
Fn1
表示文件名的参数。
# 回答10
我试过了,仍然显示没有这样的文件或目录
我试过了,仍然显示没有这样的文件或目录
# 回答11
这就是我所拥有的:
这就是我所拥有的:
选择 | 换行 | 行号
- fn1 = raw_input("What is the name of the first file (be sure to include .txt after the filename)?")
- fn2 = raw_input("What is the name of the second file (be sure to include .txt after the filename)?")
- fileobj1 = open("fn1", "r")
- fileobj2 = open("fn2", "r")
- if file1 == file2:
- print ("Yes these files are the same.")
- else:
- print("No these file are not the same.")
# 回答12
除非文件位于PYTHONPATH中,否则必须提供文件的完整路径,请参见
这里
。
除非文件位于PYTHONPATH中,否则必须提供文件的完整路径,请参见
这里
。
选择 | 换行 | 行号
- import sys
- print sys.path
- ##
- ## if the path to the file is not in the above then you have to provide the path
- fileobj1 = open("/path/to/fn1", "r")
- ##
- ## or add it to sys.path
- sys.path.append("/path/to")
- fileobj1 = open("fn1", "r")
标签: python