Connor Connor - 2 months ago 8
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 =;

I get the following errors:

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\", line 1536, in __call__
return self.func(*args)
File "", line 71, in genPimPlot
File "", line 75, in ExtractPIMDataFromFiles
for subdir, dirs, files in os.walk(rootdir):
File "C:\Python27\lib\", 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.


you can try this

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

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