rrfeva
rrfeva

Reputation: 87

read files in a directory specified by a command line argument

I am trying to read files from a directory specified by a command line argument.The command line:

./printfiles.py ./test_dir

The code I have so far is:

#!/usr/bin/env python3

import os
import sys

input_dir=argv[1]
for file in os.listdir(input_path):
    with open(file, "r") as f:
        for line in f.readlines():
            print(line)

I am getting the error:

FileNotFoundError: [Errno 2] No such file or directory: 'hello.txt'

I think that the problem is because os.listdir() only returns file names, not the path. I am confused as how to do this because the path is just specified by the user.

Upvotes: 0

Views: 31

Answers (1)

Blorgbeard
Blorgbeard

Reputation: 103447

I think that the problem is because os.listdir() only returns file names, not the path.

I think you're correct.

You can give open the full path to the file by using os.path.join:

with open(os.path.join(input_dir, file), "r") as f:

Upvotes: 1

Related Questions