Python 3.x 如何比较两个文件并查看内容是否相同?
我目前正在编写一个代码,询问用户是否希望复制一个文件的内容并将其放入另一个文件中,同时比较一个文件的两个内容以查看它们是否相同。我的文件的复制部分起作用,但与比较两个文件内容的部分不起作用。我得到一个错误,说: line2=输出文件.readlines()Python 3.x 如何比较两个文件并查看内容是否相同?,python-3.x,Python 3.x,我目前正在编写一个代码,询问用户是否希望复制一个文件的内容并将其放入另一个文件中,同时比较一个文件的两个内容以查看它们是否相同。我的文件的复制部分起作用,但与比较两个文件内容的部分不起作用。我得到一个错误,说: line2=输出文件.readlines() io.UnsupportedOperation:不可读 这是我目前的代码: userinput=int(input('Press 1 to copy files, 2 to compare files, anything else to st
io.UnsupportedOperation:不可读 这是我目前的代码:
userinput=int(input('Press 1 to copy files, 2 to compare files, anything else to stop')) #prompt user for comparing or copying
while userinput==1 or userinput==2:
if userinput==1:
with open(input('Enter file you want copied:')) as input_file:
with open(input('Enter file you want contents copied to:'), 'w') as output_file:
for line in input_file: #contents of first file copied to second file
output_file.write(line)
userinput=int(input('Press 1 to copy files, 2 to compare files, anything else to stop'))
elif userinput==2:
with open(input('Enter file you want to check')) as input_file:
with open(input('Enter second file you want to check:'), 'w') as output_file:
line1=input_file.readlines() #reads each line of the text
line2=output_file.readlines()
if line1==line2: #checks if text is identical to each other
print('files are identical')
userinput=int(input('Press 1 to copy files, 2 to compare files, anything else to stop'))
elif line1 != line2:
print('This is where the file deviates')
print(line1)
print(line2)
userinput=int(input('Press 1 to copy files, 2 to compare files, anything else to stop'))
如何解决此问题?您打开了输出文件
output\u文件
进行写入('w'
)。你不能从中阅读。将'w'
更改为'r'
您试图读取文件,但您使用参数'w'以可写方式打开文件
打开(输入('输入要检查的第二个文件:'),'w')作为
输出文件:
删除参数或将'w'替换为'r'
打开时(输入('输入要检查的第二个文件:')作为
输出文件:
或
打开时(输入('输入要检查的第二个文件:'),'w')作为
输出文件: