The following piece of code works fine, reads all the text files in the specified directory:

files_ = glob.glob('D:\Test files\Case 1\*.txt')

But when I change the path to another directory, it gives me an empty list of files:

files_ = glob.glob('D:\Test files\Case 2\*.txt')
print files_ >> []

Both directories contain a couple of text files. Text file names and sizes are different though. It's really wired and I couldn't think of any thing to solve the problem. Has anyone faced such a problem?

有帮助吗?

解决方案

You need to either escape your backslashes:

files_ = glob.glob('D:\\Test files\\Case 2\\*.txt')

Or specify that your string is a raw string (meaning backslashes should not be specially interpreted):

files_ = glob.glob(r'D:\Test files\Case 2\*.txt')

What happened to break your second glob is that \1 turned into the ASCII control character \x01. The error message contains a clue to that:

WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect: 'D:\\Test files\\B1\x01rgb/*.*'

Notice how a \1 turned into the literal \x01. The reason your first directory worked is that you basically got lucky and didn't accidentally specify any special characters:

'\T'
Out[27]: '\\T'

'\B'
Out[28]: '\\B'

'\1'
Out[29]: '\x01'
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top