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

问题描述 投票:0回答:1

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

提前致谢。

linux python-3.x file filesystems
1个回答
1
投票

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

以下对我有用

import os

path = input("enter filepath: ")

for f in os.listdir(os.path.expanduser(path)):
    print(f)
© www.soinside.com 2019 - 2024. All rights reserved.