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

时间:2011-12-07 13:47:58

标签: python file select directory-listing

我想通过列表左侧的数字选择一个文件,但我不能超过这个:

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

提前谢谢..

6 个答案:

答案 0 :(得分:2)

您应该对列表使用枚举,然后处理输入错误。理想情况下,这将是一个函数,而不是执行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)

答案 1 :(得分:1)

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

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

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

答案 2 :(得分:0)

您可以尝试以下方法:

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!

应该这样做:)

答案 3 :(得分:0)

您知道特定索引处的文件名,因此您可以执行以下操作:

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

for index in range(0,len(dirList)):
    print str(index+1) + ": " + dirList[index]

selected = raw_input("Select a file above: ")
print "You selected filename: " + dirList[selected];

编辑:oops to slow

答案 4 :(得分:0)

试试这个:

import os

listed_files = []
for i, fname in enumerate(os.listdir("/root/Desktop")):
    print i, ': ', fname
    listed_files.append(fname)

selected = raw_input("Select a file above: ")
open("/root/Desktop/%s" % listed_files[int(selected)])

答案 5 :(得分:0)

创建一个字典,其中键是索引,值是文件名(使用enumerate(dirList)获取每次迭代的元组(索引,文件名))。然后根据输入(键)拉出相应的值。