我试图从命令行参数指定的目录中读取文件。命令行:
./printfiles.py ./test_dir
我到目前为止的代码是:
#!/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)
我收到错误:
FileNotFoundError: [Errno 2] No such file or directory: 'hello.txt'
我认为问题是因为os.listdir()只返回文件名,而不是路径。我很困惑如何做到这一点,因为路径只是由用户指定。
我认为问题是因为os.listdir()只返回文件名,而不是路径。
我认为你是对的。
您可以使用open
为os.path.join
提供文件的完整路径:
with open(os.path.join(input_dir, file), "r") as f: