Connor Connor - 28 days ago 5
Python Question

(SOLVED) How do I avoid Python Unicode encoding error when reading in a text file?

I have written the following Python code, which uses the folder selected by the user (data_fold) to navigate through the text files in the folder that contain the data.

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;


I get the following errors:

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


I need the code to do a few things: open the file, read the data in, add the data to a dictionary, close the file. I am new to Python, so explicit solutions would be greatly appreciated. Thank you for your time and expertise.

Answer

you can try this

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)

output: {'file1':'data','file2':'data',.......}

Comments