我当前正在编写一个代码,询问用户是否要复制文件的内容并将其放入另一个文件,还比较文件的两个内容以查看它们是否相同。我文件的复制部分有效,但比较两个文件内容的部分无效。我收到一条错误消息:
line2 = output_file.readlines()
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'))
该如何解决?
答案 0 :(得分:0)
您已打开输出文件<FormGroup row>
<Col md={6}>
<Select
placeholder={label}
name={fieldName}
onChange={method1}
options={options}
display="none" />
</Col>
</FormGroup>
进行写入(file = input("Enter the file name: ")
text_file = open(file, "r")
lines = text_file.readlines()
print (len(lines))
while True:
linenumber = int(input("Please enter a line number or press 0 to quit: "))
if linenumber == 0:
print("Thanks for using the program")
break
elif 1 <= linenumber <= len(lines) :
print (lines[linenumber- 1])
else:
print("Please enter valid line number")
text_file.close()
)。您无法阅读。将output_file
更改为'w'
。
答案 1 :(得分:0)
您正在尝试读取文件,但是您使用参数'w'
以可写方式打开文件与open(input('输入要检查的第二个文件:'),'w')为 output_file:
删除参数或将'w'替换为'r'
与open(input('输入要检查的第二个文件:'))为 output_file:
OR
与open(input('输入要检查的第二个文件:'),'w')为 output_file: