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

2024-03-28 14:58:49 发布

您现在位置: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

请提前帮助和感谢


Tags: andtheinsourceinputlinedestinationutf
2条回答
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")

正如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打开文件,因为它会自动关闭文件。你知道吗

相关问题 更多 >