[英]Python - reading from file into a list
This is simple but I just cant seem to get it right. 这很简单,但我似乎无法做到正确。
I have a text file containing numbers in the form 我有一个包含表格中数字的文本文件
0 1 2
3 43
5 6 7 8
and such. 等等。
I want to read these numbers and store it in a list such that each number is an element of a list. 我想读取这些数字并将其存储在列表中,以便每个数字都是列表的元素。 If i read the entire file as a string, how can I split the string to get these elements separated?
如果我将整个文件作为字符串读取,我如何拆分字符串以将这些元素分开?
Thanks. 谢谢。
You can iterate over the file object as if it were a list of lines: 您可以迭代文件对象,就好像它是一个行列表:
with open('file.txt', 'r') as handle:
numbers = [map(int, line.split()) for line in handle]
A slightly simpler example: 一个稍微简单的例子:
with open('file.txt', 'r') as handle:
for line in handle:
print line
First, open the file. 首先,打开文件。 Then iterate over the file object to get each of its lines and call split() on the the line to get a list of strings.
然后遍历文件对象以获取其每一行并在该行上调用split()以获取字符串列表。 Then convert each string in the list to a number:
然后将列表中的每个字符串转换为数字:
f = open("somefile.txt")
nums = []
strs = []
for line in f:
strs = line.split() #get an array of whitespace-separated substrings
for num in strs:
try:
nums.append(int(num)) #convert each substring to a number and append
except ValueError: #the string cannot be parsed to a number
pass
nums now contains all of the numbers in the file. nums现在包含文件中的所有数字。
how can I split the string to get these elements separated
如何拆分字符串以分离这些元素
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.