Pierfrancesco
Pierfrancesco

Reputation: 87

Reading a file from directory

I am trying to read a file in the directory ./resources/input_file.utf8. However, when I compile the following code from the terminal with the command:

 python namefile.py input

this error appears:

[Errno 2] No such file or directory: 'input'

This is my code:

from argparse import ArgumentParser


def parse_args():
    parser = ArgumentParser()
    parser.add_argument("input_path", help="./resources/input_file.utf8")

    return parser.parse_args()


def foo(input_path):

    file_input = open(input_path, "r", encoding='utf-8-sig') 
    for line in file_input:
    [...]


if __name__ == '__main__':
    args = parse_args()
    predict(args.input_path)

One of the specification I have to respect is to not to put hard paths directly in the foo function, but only in the parser.add_argument() function.

How can I fix it?

Upvotes: 0

Views: 50

Answers (1)

DobromirM
DobromirM

Reputation: 2027

If you are running the command python namefile.py input, make sure that:

1) Files - You have both your input file and the python script in the same folder.

2) Location - The working directory in you terminal is the one that contains the files (use pwd to check).

3) File name - Your filename is exactly input and not input.txt or input.utf8.


If your file is in the path that you have provided in your example, then you would need to call the script with that path.

Example:

python namefile.py "./resources/input_file.utf8"

Upvotes: 1

Related Questions