开发者

Python - issues with numbers in pathnames

I need to open all PDFs in a certain directory, so I first generate a list of the file paths using os.path:

filenames = [
    normpath(join(directoryname, filename))
    for filename in listdir(directoryname)
    if filename.lower().endswith('.'+extension)            
    ]

So an item in that list looks like this: D:\\Folder\\2010\\file.pdf

Then I'd like to open each file in a for-loop:

for file in filenames:
    PdfFileReader(file(file, 'rb'))

but there seems to be an issue with the 2010, because I get this erro开发者_运维百科r:

IOError: [Errno 2] No such file or directory: 'D:\\Folder\\x810\\file.pdf'

I'd like to do something along the lines of

PdfFileReader(file(r'D:\\Folder\\2010\\file.pdf', 'rb'))

how would I do that in the above example where the path is passed as a variable? Or are there any better ways to do this?

I'm using Windows and Python 2.6.

Thanks in advance!


The backslash is special in C-style strings like Python uses, just like in C++, C#, and Java. Either use a double-backslash to say “yes, I really mean a backslash,” not the character code \201, or use an r'' string that does not interpret backslash sequences:

'D:\\Folder\\2010\\file.pdf'
r'D:\Folder\2010\file.pdf'

Note that this issue does NOT come up with variables! Once you create a string correctly, it always keeps its value; it does NOT get re-interpreted, and have backslashes cause problems all over again, each time you pass the value to a function, so open(myvar) should see exactly the same string you get when you print(myvar).

(I think that on Windows you may also be able to just use forward slashes, which require no special quoting:)

'D:/Folder/2010/file.pdf'


Python automatically converts forward slashes to back slashes in Windows pathnames (This is because other OSes that Python runs on, including Linux and Mac, use forward slashes natively).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜