在Python中从键盘打开文件
我想在一个特定文件夹里的 .txt 文件上运行一个脚本。这个文件夹里的文件会不断变化,我想列出这些文件,并通过键盘输入选择一个。
这是我目前写的代码,
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
这样我就能得到一个可以分析的文件列表。
大概是这样的,
可用的文件: ['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',...]
不过,输入文件名对我来说是个不错的开始。
2 个回答
1
看起来你在寻找 in
这个关键词。你可以检查一下像这样的内容:
if choice in files:
#Do whatever you want with that filename
或者你可以考虑先生成一个字典,用文件名作为输入的键。比如:
my_key_dict={}
for count,entry in enumerate(files):
my_key_dict[count]=entry
然后再检查你的输入:
if choice in my_key_dict:
filename=my_key_dict[choice]
当然,你还需要以某种方式从 my_key_dict
生成一个列表给用户。
1
这里有一个简单的解决方案来帮你解决问题:
import glob
files = glob.glob("*.txt")
files.sort()
print "select file:"
for index, filename in enumerate(files):
print index, filename
print "enter number of file to work on:",
number = int(raw_input())
print "working on file: ", files[number]
请注意,我使用了“glob”模块,这样可以更简单地找到Txt文件,而不是通过循环来一个个匹配。我没有处理用户输入的错误,因为这个输入会通过int()函数自动转换成整数。最后,数字现在是从零开始的。如果你想让它们从一开始,可以在显示的时候加1,而在处理用户输入的时候减1。