这是代码:
print ("Enter first the source file and then destination file with respective format")
t=input() #Enter source file
t1=input() #Enter destination file
print ("Enter the keyword which has to be copied into another file")
find=input() #Enter the keyword which has to be copied
f=open(t,encoding="utf-8") #Open the source file
f1=open(t1,"a+",encoding="utf-8") #Open the destination file in append and read mode
Copy_Lines=False
for line in f.readlines():
if find in line:
Copy_Lines=True
if Copy_Lines:
f1.write(line)
f1.close()
f.close()
print("Task completed")
但是我收到了这个错误,而我却无法找到问题
Traceback (most recent call last):
File "C:\Users\sanket_d\Desktop\python files\COPY_ONE.py", line 13, in <module>
for line in f.readlines():
File "C:\Python34\lib\codecs.py", line 313, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd0 in position 0: invalid continuation byte
请提前帮助和谢谢
答案 0 :(得分:0)
print ("Enter first the source file and then destination file with respective format")
t=input() #Enter source file
t1=input() #Enter destination file
print ("Enter the keyword which has to be copied into another file")
find=input() #Enter the keyword which has to be copied
f=open(t) #Open the source file
f1=open(t1,"a+") #Open the destination file in append and read mode
Copy_Lines=False
for line in f.readlines():
if find in line:
Copy_Lines=True
if Copy_Lines:
f1.write(line)
f1.close()
f.close()
print("Task completed")
答案 1 :(得分:0)
由于Martijn Pieters评论你的文件不是utf-8
编码的,我已经重写了你的代码,使其更符合pep-8风格指南并且更具可读性:
print("Enter first the source file and then destination file with respective format")
t = input() # Enter source file
t1 = input() # Enter destination file
print("Enter the keyword which has to be copied into another file")
find = input() # Enter the keyword which has to be copied
with open(t) as f, open(t1, "a+") as f1: # Open the source file and open the destination file in append and read mode
copy_lines = False
for line in f.readlines():
if find in line:
copy_lines = True
if copy_lines:
f1.write(line)
print("Task completed")
对于使用下划线_
分隔单词的变量名称,请使用小写。
在copy_lines = False
而非copy_lines=False
之类的作业和#
与您的评论之间留出空格,例如# mycomment
而不是#mycomment
。
使用with
打开文件,因为它会自动关闭文件。