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

0 投票
6 回答
682 浏览
提问于 2025-04-17 07:53

我想通过列表左边的数字来选择文件,但我只能做到这个:

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 个回答

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

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

这样应该就能解决问题了 :)

撰写回答