在Python中读取文件的数据?
问题描述:
我有一个文件说input.txt
其中包含下列格式的数据::在Python中读取文件的数据?
[8, 3, 4, 14, 19, 23, 10, 10, "Delhi"]
13
"Delhi"
8
10
19
我怎么能看在Python或Ruby的数据。我可以看到我的第一行包含包含整数和字符串的数据。 而且我该如何储存它?
答
我给你举个例子:
with open(fname) as f:
content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
content = [x.strip() for x in content]
注:列表:内置的Python序列。尽管它的名字更像 到其他语言的数组而不是链接列表,因为对 元素的访问是O(1)。
+0
你需要更多的细节看到这个http://stackoverflow.com/questions/10393176/is-there-a-way-to-read-a-txt-file-and-store-each-line-to-memory –
答
如果你信任你的输入文本文件的来源,那么我注意到,每一行是一个有效的Python表达式,所以你可以这样做:
with open(filename) as txt:
evaluated_lines = [eval(line) for line in txt if line.strip()]
print(evaluated_lines)
输出:
[[8, 3, 4, 14, 19, 23, 10, 10, 'Delhi'], 13, 'Delhi', 8, 10, 19]
请注意,Python列表数据类型可以包含子列表,整数和字符串的混合
对于第一行,我应该将哪个数据结构se存储整数和字符串数据类型? –
http://stackoverflow.com/questions/14676265/how-to-read-text-file-into-a-list-or-array-with-python看到这个。它有助于你 –