Python csv文件读写

图是题目和我写的代码,在第五行报错显示‘UnicodeDecodeError: 'gbk' codec can't decode byte 0x85 in position 28: illegal multibyte sequence’是哪里出了问题,应该怎么解决呢,在统计次数时,文件中是‘12345次’怎么去除‘次’的影响做统计判断,正确的代码可以怎么写

img

  • 你可以参考下这个问题的回答, 看看是否对你有帮助, 链接: https://ask.csdn.net/questions/7775405
  • 这篇博客也不错, 你可以看下Python读取CSV文件:UnicodeDecodeError: 'gbk' codec can't decode byte 0xba ....illegal multibyte sequence
  • 除此之外, 这篇博客: Python: 使用open函数报错:‘gbk‘ codec can‘t decode byte 0x80 in position 8: illegal multibyte sequence中的 问题描述: 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • 想写一个脚本用来将指定目录下的文件内容拷贝到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:
    

    在这里插入图片描述
    搜索了全网,大都归咎于:变量重复定义,但是我找了好久也没发现重定义的地方。