New to Programming: TypeError: coercing to Unicode: need string or buffer, list found

Peter Otten __peter__ at web.de
Thu Apr 2 14:26:21 CEST 2015


Saran A wrote:

> Good Morning:
> 
> I understand this error message when I run this code. However, I am
> curious to know what the most pythonic way is to convert  the list to a
> string? I use Python 2.7.
> 
> "Traceback (most recent call last):
> before = dict([(f, None) for f in os.listdir(dirlist)])
> TypeError: coercing to Unicode: need string or buffer, list found"
> 
> 
> The sample code that I am trying to run is:
> 
> path = "/Users/Desktop/Projects/"
> dirlist = os.listdir(path)

At this point dirlist is a list of names of the files and directories in 

"/Users/Desktop/Projects/"

Assuming that the Projects folder contains the subfolders or files
/Users/Desktop/Projects/foo, /Users/Desktop/Projects/bar and 
/Users/Desktop/Projects/baz dirlist looks like this:

["foo", "bar", "baz"]

It makes no sense to pass this list to os.listdir() as you do below:

> before = dict([(f, None) for f in os.listdir(dirlist)])

Forget about the other details in the error message; the actual problem is 
the "list found" part.

Now what would be a possible fix? Sorry, I have no idea what your intention 
is. Again, you don't need to convert your list to string, you need to decide 
what directory you want to pass to listdir(). If you have multiple such 
directories you need to invoke listdir() multiple times with a single 
directory, typically in a loop.

Bonus info:

>     while True:
>         time.sleep(10) #time between update check
 
This loop will never terminate.




More information about the Python-list mailing list