【问题标题】:How to convert users input to file path in Python如何在 Python 中将用户输入转换为文件路径
【发布时间】:2018-09-15 09:47:59
【问题描述】:

我目前正在尝试获取 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/'

提前致谢。

【问题讨论】:

  • 您的代码在我的机器上运行。您确定要查找的目录存在吗?
  • 哦。我正在尝试使用任何目录。
  • 在您的第一部分代码中,您将路径变量声明放在 if 中,但您在 if 块之外使用它,因此无法初始化变量。事实上,如果你不插入任何参数,你的代码就不起作用。
  • 对于代码的第一部分,您必须像这样运行它,python3 script_name.py ~/backup/ 因为它从 sys arg 获取参数。我以为我说清楚了。

标签: linux python-3.x file filesystems


【解决方案1】:

您需要像question 的答案一样扩展~

以下对我有用

import os

path = input("enter filepath: ")

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

【讨论】:

  • 没问题!乐于助人!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-06
  • 2016-07-26
  • 1970-01-01
  • 2012-09-30
  • 1970-01-01
相关资源
最近更新 更多