TMikonos
TMikonos

Reputation: 369

Check if a file exists with pathlib in Python and it returns a false negative

I am passing through ArgumentParser a path to files and check if the file is valid to run it. However, with a file, pathlib returns when check if exists. The file is called: OC POC G4 W49 DB3 KIDS WE UK NOR Translations_Spanish and Portuguese Claims Missing.xlsx and is in the path let's say it is at:

c:\OC POC G4 W49 DB3 KIDS WE UK NOR Translations_Spanish and Portuguese Claims Missing.xlsx

The location of the file can be anywhere, also tried with absolute and relative paths, the file for pathlib does not exist.

I have this code for the arguments:

from argparse import ArgumentParser
from pathlib import Path
args_parser = ArgumentParser()
args_parser.add_argument('path', 
                         help='Path to the Excel files to prepare', nargs='+')
args = args_parser.parse_args()
if args.path:
    for file in args.path:
        pth = Path(file).resolve()
        print(pth, pth.exists()) # return False for this file

The result is that the file does not exist. While it exists. I don't understand why is it happening. I guess it is some interference with the argument parser, but I cannot guess the cause.

Upvotes: 0

Views: 3031

Answers (1)

Seth
Seth

Reputation: 2369

If you pass in an argument with spaces in it, you need to surround it with quotation marks ("), so it knows that you're not passing in multiple arguments. Also, as a general rule of thumb, don't include spaces in filenames.

Upvotes: 1

Related Questions