在读取文本文件时如何避免Python Unicode编码错误?

时间:2016-10-27 18:52:16

标签: python python-2.7

我编写了以下Python代码,该代码使用用户选择的文件夹(data_fold)来浏览包含数据的文件夹中的文本文件。

rootdir = self.data_fold;
   for subdir, dirs, files in os.walk(rootdir):
        for file in files:
            file2read = open(os.path.join(subdir, file));
            data = file2read.read();                       
            file2read.close();
            data;

我收到以下错误:

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1536, in __call__
return self.func(*args)
File "PIM_Reporter.py", line 71, in genPimPlot
self.ExtractPIMDataFromFiles(self.data_fold);
File "PIM_Reporter.py", line 75, in ExtractPIMDataFromFiles
for subdir, dirs, files in os.walk(rootdir):
File "C:\Python27\lib\os.py", line 278, in walk
names = listdir(top)
TypeError: coercing to Unicode: need string or buffer, list found

我需要代码做一些事情:打开文件,读取数据,将数据添加到字典中,关闭文件。我是Python的新手,因此非常感谢显式解决方案。感谢您的时间和专业知识。

1 个答案:

答案 0 :(得分:-1)

你可以试试这个

import os
d = {}
for root, dirs, files in os.walk('path'):
    for file in files:
        print(file)
        with open(os.path.join(root,file)) as f:
            d[file]= f.read()
            f.close()
print(d)

<强>输出: { '文件1': '数据', '文件2': '数据',.......}