I don’t seem to be able to open a file which has a unicode filename. Lets say I do:
for i in os.listdir():
open(i, 'r')
When I try to search for some solution, I always get pages about how to read and write a unicode string to a file, not how to open a file with file() or open() which has a unicode name.
Simply pass
open()a unicode string for the file name:In Python 2.x:
In Python 3.x, all strings are Unicode, so there is literally nothing to it.
As always, note that the best way to open a file is always using the
withstatement in conjunction withopen().Edit: With regards to
os.listdir()the advice again varies, under Python 2.x, you have to be careful:Source
So in short, if you want Unicode out, put Unicode in:
Note that the file will still open either way – it won’t be represented well within Python as it’ll be an 8-bit string, but it’ll still work.
Under 3.x, as always, it’s always Unicode.