我有一个包含以下内容的输入文件:
1a 2a 2b 2c 2d 3a 3b 3c 3d
我的Python代码如下:
f = open('access.txt', 'r')
controls = f.read()
for line in controls:
s = line.split()
print(s),
我期望格式为['1a','2a','2b'b, ...]
的数组。但我得到的是一种不同的格式,所有print
两次:
['1'] ['a'] [] ['2'] ['a'] [] ['2'] ['b'] [] ['2'] ['c'] [] ['2'] ['d'] [] ['3'] ['a'] [] ['3'] ['b'] [] ['3'] ['c'] [] ['3'] ['d'] [] [] ['1'] ['a'] [] ['2'] ['a'] [] ['2'] ['b'] [] ['2'] ['c'] [] ['2'] ['d'] [] ['3'] ['a'] [] ['3'] ['b'] [] ['3'] ['c'] [] ['3'] ['d'] [] []
我似乎无法确定这两个问题。
编辑:看起来我正逐字逐句地进行迭代,我已经修复了。
答案 0 :(得分:1)
你可以试试这个:
# automatically closes file when done
with open('access.txt', 'r') as f:
for line in f.readlines():
s = line.split()
print(s),
这样你就可以逐行循环,并逐个分割每一行。
答案 1 :(得分:0)
您的for循环将整个文件内容循环为一个字符串,每次一个字符。在阅读文件时,您可以通过执行以下操作来保留大部分代码:
controls = f.read().splitlines().
从那里你可以像你已经做的那样循环。
如果您的文件只有一行,那么您可以这样做:
f.read().split()
答案 2 :(得分:0)
如果您想要一个行列表,请使用readlines
代替read
。
答案 3 :(得分:0)
您可以使用readlines()
with open('data','r') as f:
controls = f.readlines()
for line in controls:
s = line.split()
print(s, end=" "),
['1a', '2a', '2b', '2c', '2d', '3a', '3b', '3c', '3d']
答案 4 :(得分:0)
因为您尝试在字符串上使用for
。我们来看看:
f = open('access.txt', 'r')
controls = f.read()
现在发生了什么? controls
是一个字符串,因为您使用的是f.read()
因此,在字符串上使用for
循环会给出类似......你可以在Python Shell中尝试它。
实际上你在这里不需要f.read()
,以下代码可以正常工作:
with open('access.txt', 'r') as f: # with can auto close the file, it's safe.
for line in f:
s = line.split()
print(s, end='')
此外,这是一种使用 list comprehension 的简单方法:
with open('access.txt', 'r') as f:
print(*[s.split() for s in f])