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

Dave Angel davea at davea.name
Thu Apr 2 22:18:52 CEST 2015


On 04/02/2015 08:28 AM, Saran Ahluwalia 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)
 > before = dict([(f, None) for f in os.listdir(dirlist)])


You have two calls to listdir in the code you quote here.  Once you've 
called os.listdir(path)  you get back a list of filenames.  Why you then 
call os.listdir again on that list I have no clue.  And I also have no 
idea what you think the dict is going to do.


>
> def main(dirlist):
>      while True:
>          time.sleep(10) #time between update check
>      after = dict([(f, None) for f in os.listdir(dirlist)])
>      added = [f for f in after if not f in before]
>      if added:
>          print('Successfully added new file - ready to validate')
> if __name__ == "__main__":
>      main()

You didn't run that code, as this call to main() passes no arguments. 
Last time I saw your whole file, it had two separate  if __name__ == 
"__main__" clauses.  So you'd better make sure one of them is commented 
out, or it'll keep confusing you.

First thing is to pick better names.  And second is to add a comment to 
each function as to what it expects for arguments.  main() expects a 
directory name, so rename the dirlist variable to something like path.

Then figure out what the argument to main() should look like.  it should 
not be  sys.argv[1:], as that's a list.  You want a single item on the 
command line specifying the path.


This whole thing with 'before' and 'after' is the long way around. 
Since you're going to move files from this directory after you analyze 
them, all you need to do is call os.listdir again each time through the 
loop.  Anything you find will be new, by definition.

Then once you have your list, you do NOT want to loop through it, as 
you're going to be calling a function (already written by you) that 
wants a list of filenames.

Incidentally you posted some code earlier, in yet another new thread, 
that calls copyfile() from the function move_to_failure_folder(). 
Shouldn't that function be called movefile()?  and shouldn't it use a 
different shutil function?

-- 
DaveA


More information about the Tutor mailing list