图是题目和我写的代码,在第五行报错显示‘UnicodeDecodeError: 'gbk' codec can't decode byte 0x85 in position 28: illegal multibyte sequence’是哪里出了问题,应该怎么解决呢,在统计次数时,文件中是‘12345次’怎么去除‘次’的影响做统计判断,正确的代码可以怎么写
想写一个脚本用来将指定目录下的文件内容拷贝到txt文档内,源码如下:
import os
f = open("./test_name.txt",'w') #先创建一个空的文本
path ="D:/Users/Documents/Pratices" #指定需要读取文件的目录
files =os.listdir(path) #采用listdir来读取所有文件
files.sort() #排序
s= [] #创建一个空列表
for file_ in files: #循环读取每个文件名
print(path+" "+file_)
if not os.path.isdir(path +file_): #判断该文件是否是一个文件夹
f_name = str(file_)
print(f_name)
with open(('D:/Users/Documents/Pratices/%s'%f_name), "r",encoding = 'utf-8') as ff:
lines = ff.readlines()
for line in lines:
line = line.strip()
print(line)
''' a 打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容
将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入'''
with open(('D:/Users/Documents/Pratices/%s'%f_name+'.txt'), "a",encoding = 'utf-8') as ww:
ww.write(line+'\n')
s.append(f_name) # 把当前文件名返加到列表里
f.write(f_name + '\n') # 写入之前的文本中
print(s) #看一下列表里的内容
当执行到此处的时候报错
with open(('D:/Users/Documents/Pratices/%s'%f_name), "r") as ff:
搜索了全网,大都归咎于:变量重复定义,但是我找了好久也没发现重定义的地方。