我想在给定目录中的.txt文件上运行脚本。该文件夹中的文件将发生变化,我有兴趣列出它们并通过键盘输入选择一个文件。从Python中的键盘打开文件
这是我到目前为止的代码,
import os
folder = os.getcwd() #Current directory
files = [f for f in os.listdir(folder) if f.endswith('.txt')]
print 'Files available:\n %r' % files
这将使我,我可以分析文件的列表的输出。
STH这样,
文件可用的:['file.txt的', 'foo.txt的', '的Test.txt']
而现在的代码段我卡在其中:
while True:
print "Introduce the name of the file"
choice = raw_input()
if choice.lower() == 'FILE FROM THE LIST':#Here's where I'm stuck
with open('FILE FROM THE LIST', 'rt') as inputfile:
data = csv.reader(inputfile)
#Do stuff
elif choice.lower() == 'e':
break
else:
print "Please, choose a valid option or type 'e' to exit"
我应该怎么做才能输入文件名并从那里运行脚本?
理想情况下,我想在列出的文件和一个密钥或数字之间创建一个链接,使其更短,例如
[输入 '1' 来打开FILE.TXT,
类型 '2' 以打开foo.txt的,
类型 '3' 打开 'TEXT.TXT',...]
但是输入名字对我来说是一个很好的方式。
这对于我想要的是完美的。非常感谢你。 –