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

时间:2018-09-15 09:48:00

标签: linux python-3.x file filesystems

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

此代码目前仅适用于基于unix的操作系统。

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/'

谢谢。

1 个答案:

答案 0 :(得分:1)

您需要像对此question的答案一样展开~

以下内容对我有用

import os

path = input("enter filepath: ")

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