Python 如何将用户输入转换为文件路径

How to convert users input to file path in Python

我目前正在尝试获取 file_path (suppose ~/hello_world/) 作为用户输入并列出该目录中的所有文件。如果我将 ~/hello_world 作为 sys.argv 传递,我可以做同样的事情,但是,如果我将它作为输入,我似乎无法让它工作。我正在尝试从任何目录处理代码,用户输入的文件路径将来自 /home/ubunut/... 这是我的工作代码 sys.argv:

此代码目前仅适用于基于 unix 的 os。

if len(sys.argv) == 2:
    path = sys.argv[1]

files = os.listdir(path)
for name in files:
    print(name)

这是我尝试使用的代码:

path = input("file_path: ")
files = os.listdir(path)
for name in files:
    print(name)

这是崩溃并出现以下错误:

Traceback (most recent call last):
  File "test.py", line 14, in <module>
    files = os.listdir(path)
FileNotFoundError: [Errno 2] No such file or directory: '~/hello_world/'

提前致谢。

你需要像这个 question

的答案一样扩展 ~

以下对我有用

import os

path = input("enter filepath: ")

for f in os.listdir(os.path.expanduser(path)):
    print(f)