Python—从文件读入列表
这很简单,但我似乎做不好 我有一个文本文件,其中包含表单中的数字Python—从文件读入列表,python,Python,这很简单,但我似乎做不好 我有一个文本文件,其中包含表单中的数字 0 1 2 3 43 5 6 7 8 诸如此类 我想读取这些数字并将其存储在一个列表中,这样每个数字都是列表的一个元素。如果我将整个文件作为字符串读取,如何拆分字符串以将这些元素分开 谢谢。您可以迭代文件对象,就像它是一个行列表一样: with open('file.txt', 'r') as handle: numbers = [map(int, line.split()) for line in handle]
0 1 2
3 43
5 6 7 8
诸如此类
我想读取这些数字并将其存储在一个列表中,这样每个数字都是列表的一个元素。如果我将整个文件作为字符串读取,如何拆分字符串以将这些元素分开
谢谢。您可以迭代文件对象,就像它是一个行列表一样:
with open('file.txt', 'r') as handle:
numbers = [map(int, line.split()) for line in handle]
一个稍微简单的例子:
with open('file.txt', 'r') as handle:
for line in handle:
print line
如何拆分字符串以分离这些元素
首先,打开文件。然后迭代file对象以获取其每一行,并在该行上调用split()以获取字符串列表。然后将列表中的每个字符串转换为数字:
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现在包含文件中的所有数字。是否要将数字存储为整数或字符串?我认为这里不适用regex标记…愚蠢的标记已经被修复。哇。以前从未见过这种语法!