Python 将文本文件中的行读入变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27407571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read lines from a text file into variables
提问by Viva
I have two different functions in my program, one writes an output to a txt file (function A) and the other one reads it and should use it as an input (function B).
我的程序中有两个不同的函数,一个将输出写入 txt 文件(函数 A),另一个读取它并将其用作输入(函数 B)。
Function A works just fine (although i'm always open to suggestions on how i could improve). It looks like this:
功能 A 工作得很好(尽管我总是乐于接受有关如何改进的建议)。它看起来像这样:
def createFile():
fileName = raw_input("Filename: ")
fileNameExt = fileName + ".txt" #to make sure a .txt extension is used
line1 = "1.1.1"
line2 = int(input("Enter line 2: ")
line3 = int(input("Enter line 3: ")
file = (fileNameExt, "w+")
file.write("%s\n%s\n%s" % (line1, line2, line3))
file.close()
return
This appears to work fine and will create a file like
这似乎工作正常,并会创建一个文件
1.1.1
123
456
Now, function B should use that file as an input. This is how far i've gotten so far:
现在,函数 B 应该使用该文件作为输入。这是到目前为止我已经走了多远:
def loadFile():
loadFileName = raw_input("Filename: ")
loadFile = open(loadFileName, "r")
line1 = loadFile.read(5)
That's where i'm stuck, i know how to use this first 5 characters but i need line 2 and 3 as variables too.
这就是我卡住的地方,我知道如何使用前 5 个字符,但我也需要第 2 行和第 3 行作为变量。
回答by Jo?o Paulo
f = open('file.txt')
lines = f.readlines()
f.close()
lines
is what you want
lines
是你想要的
Other option:
其他选择:
f = open( "file.txt", "r" )
lines = []
for line in f:
lines.append(line)
f.close()
More read:
更多阅读:
https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
回答by Joran Beasley
from string import ascii_uppercase
my_data = dict(zip(ascii_uppercase,open("some_file_to_read.txt"))
print my_data["A"]
this will store them in a dictionary with lettters as keys ... if you really want to cram it into variables(note that in general this is a TERRIBLEidea) you can do
这会将它们存储在以字母为键的字典中......如果你真的想把它塞进变量中(请注意,通常这是一个可怕的想法)你可以这样做
globals().update(my_data)
print A