如何使用varible打开文件

时间:2015-12-08 20:36:08

标签: python file variables python-3.4

我正在尝试使用变量打开文件,我可以使用if语句来查找要打开的文件,但只需要使用变量就可以轻松10倍找出要打开的内容。下面的代码不是完整的代码,但它是我想要做的。可悲的是,这种尝试并没有像我希望的那样好,但是它让你知道它会做什么。

name = "Jacob"
door = "me"
print (name)

File = open (name".txt","r")#opens the Little file
Little = []#creates Little list
Little = File.read().splitlines()#adds what is in Little file to Little list
print (Little)

2 个答案:

答案 0 :(得分:2)

这是你想要实现的目标吗?

name = "Jacob.txt"
with open(name,'r') as f:
    content = [ line for line in f]
    print content

答案 1 :(得分:1)

应该是:

File = open (name + ".txt","r")#opens the Little file

从我收集到的东西。

忘记+name之间的".txt" 祝你好运!

相关问题