从Python中指定的目录中选择文件

2024-10-01 13:26:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我只想在左边选择一个文件:

import os
path="/root/Desktop"
dirList=os.listdir(path)
for fname in dirList:
    print fname

selected = raw_input("Select a file above: ")

我该怎么办?在

示例:

http://img502.imageshack.us/img502/4407/listingy.png

提前谢谢你。。在


Tags: 文件pathinimportforrawosroot
3条回答

您可以尝试以下操作:

import os
path="/root/Desktop"
dirList=os.listdir(path)
for i in range(0,len(dirList)): # generate an index an loop over it
    print "%d)" % (i+1), dirList[i] # print a selection number matching each file

selected = raw_input("Select a file above: ")
selected = int(selected) # cast the input to int

print "You have selected:", dirList[selected-1] # you can get the corresponding entry!

这应该能达到目的:)

for i, fname in enumerate(dirList):
    print "%s) %s" % (i + 1, fname)

selectedInt = int(raw_input("Select a file above: "))
selected = dirList[selectedInt - 1]

但是,请注意,没有进行错误更正。您应该捕捉输入不是整数的情况。在

您应该对列表使用枚举,然后处理输入错误。理想情况下,这将是一个函数,而不是执行break操作,而是返回选定的文件。在

import os

path="/root/Desktop"
dirList=os.listdir(path)

for i, fname in enumerate(dirList):
    print "%d) %s" % (i + 1, fname)

while True:
    try:
        selectedInt = int(raw_input("Select a file above: "))
        selected = dirList[selectedInt - 1]
        break
    except Exception:
        print "Error: Please enter a number between 1 and %d" % len(dirList)

相关问题 更多 >