Python:使用用户输入作为目录名称列出目录不起作用
我一整天都在努力解决这个问题。我只想列出用户指定的目录中的文件。以下是我的代码和回溯:
>>> os.listdir(r'{}'.format(input('directory:')))
directory:C:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
WindowsError: [Error 123] The filename, directory name, or volume label syntax i
s incorrect: 'C:\r\\*.*'
任何帮助将不胜感激,谢谢!
I've been trying to solve this problem all day. I just want to list the files within a directory that a user will specify. Below is my code and traceback:
>>> os.listdir(r'{}'.format(input('directory:')))
directory:C:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
WindowsError: [Error 123] The filename, directory name, or volume label syntax i
s incorrect: 'C:\r\\*.*'
Any help would be greatly appreciated, thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要以字符串格式给出
C:
。它对我来说工作正常
,或者尝试使用
raw_input
。如果您使用的是
python3
,则raw_input
将被input
替换。You need to give
C:
in string format.Its working fine for me
or try using
raw_input
.If you are using
python3
thanraw_input
is replaced byinput
.我猜错误在于使用
input
而不是raw_input
。如果您使用
input
python 会尝试解析用户输入的文本。在您的情况下,您只想获得用户输入的字符串,因此您要么必须在字符串中添加引号(就像 RanRag 在他的答案中所做的那样),要么您可以简单地使用raw_input
因为它返回用户以字符串形式输入的字符。I guess that the error lies in the use of
input
instead ofraw_input
.If you use
input
python tries to parse the text the user entered. In your case you just want to have the string the user enters, so you either have to add quotes to the string (like RanRag did in his answer), or you could simply useraw_input
as it returns the characters the user typed as a string.正如兰拉格所说。但由于您已经从 raw_input 获取了一个字符串,因此您可以这样做:
As RanRag said. But since you'll already get a string from raw_input you can do it like this: