从doc文件复制特定关键字并将其保存到.txt文件中

时间:2014-08-01 18:41:30

标签: python

这是代码:

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

请提前帮助和谢谢

2 个答案:

答案 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打开文件,因为它会自动关闭文件。