Python: FileNotFoundError, from glob output, full path to file is correct

Viewed 279

I hate to be the person to post another FileNotFoundError question, but most of them that I see are about not giving the full path to the file, that is not my problem here.

I have a number of log files in folders in ../../Data/. I create a glob of those files using

DataFiles = glob('../../Data/2021*/*.log')

I want to open each of the files in that glob, so I use

for i, file in enumerate(DataFiles):
    with open(file, "r") as f:
...

etc. 99% of these open correctly and the rest of the code runs. For some reason, a few will not. I get an error like

FileNotFoundError: [Errno 2] No such file or directory: '../../Data\\20210629_081706\\20210629_081706_data.log'

The file definitely exists, that's why it was found by glob. The full path is used. And,

from pathlib import Path
Path('../../Data\\20210629_081706\\20210629_081706_data.log')

returns

WindowsPath('../../Data/20210629_081706/20210629_081706_data.log')

So does anyone know what might be happening here?

1 Answers

A bit late, but I had the same error when using glob in a network folder with way to many levels.

There was a particular folder where some of the files caused that error, and those files couldn't even be opened by the explorer itself:

enter image description here

In my case this was caused by the path being over 260 characters in length.

You can try something like suggested here to allow handling files with larger paths, or just make sure the path is short enough for the explorer to handle it.

Related