将文本文件的一行存储为数组 python
storing one line of a text file as an array python
我有一个文本文件,内容如下:
a 1 1
b 1 1
c 1 1
d 1 1
e 1 1
f 1 1
我希望输出像 ["a", "1", "1"] 等,但它目前输出为
[a 1 1\n]
[b 1 1\n]
[c 1 1\n]
[d 1 1\n]
[e 1 1\n]
[f 1 1\n]
我的代码是
import csv
tname = input("player 1 enter your team name ")
x = "./" + tname + ".txt"
with open (x, "r") as r:
reader = csv.reader(r)
for row in r:
spec = [row]
print (spec)
无需使用 csv
模块,只需依次读取所有行,用空格分隔并将它们附加到输出列表中:
with open('input.txt', 'r') as f:
lines = f.readlines()
output = []
for line in lines:
output = output + line.split()
print(output)
这给你:
['a', '1', '1', 'b', '1', '1', 'c', '1', '1', 'd', '1', '1', 'e', '1', '1', 'f', '1', '1']
对于期望的结果是什么有些不明确。所以三个可能的答案:
with open('somefile.txt', 'r') as f:
for row in f:
print(row.strip().split())
# -> ['a', '1', '1']
['b', '1', '1']
['c', '1', '1']
['d', '1', '1']
['e', '1', '1']
['f', '1', '1']
with open('somefile.txt', 'r') as f:
print([row.strip().split() for row in f])
# -> [['a', '1', '1'],
['b', '1', '1'],
['c', '1', '1'],
['d', '1', '1'],
['e', '1', '1'],
['f', '1', '1']]
with open('somefile.txt', 'r') as f:
print([item for row in f for item in row.strip().split()])
# -> ['a', '1', '1', 'b', '1', '1', 'c', '1', '1', 'd', '1', '1', 'e', '1', '1', 'f', '1', '1']
我有一个文本文件,内容如下:
a 1 1
b 1 1
c 1 1
d 1 1
e 1 1
f 1 1
我希望输出像 ["a", "1", "1"] 等,但它目前输出为
[a 1 1\n]
[b 1 1\n]
[c 1 1\n]
[d 1 1\n]
[e 1 1\n]
[f 1 1\n]
我的代码是
import csv
tname = input("player 1 enter your team name ")
x = "./" + tname + ".txt"
with open (x, "r") as r:
reader = csv.reader(r)
for row in r:
spec = [row]
print (spec)
无需使用 csv
模块,只需依次读取所有行,用空格分隔并将它们附加到输出列表中:
with open('input.txt', 'r') as f:
lines = f.readlines()
output = []
for line in lines:
output = output + line.split()
print(output)
这给你:
['a', '1', '1', 'b', '1', '1', 'c', '1', '1', 'd', '1', '1', 'e', '1', '1', 'f', '1', '1']
对于期望的结果是什么有些不明确。所以三个可能的答案:
with open('somefile.txt', 'r') as f:
for row in f:
print(row.strip().split())
# -> ['a', '1', '1']
['b', '1', '1']
['c', '1', '1']
['d', '1', '1']
['e', '1', '1']
['f', '1', '1']
with open('somefile.txt', 'r') as f:
print([row.strip().split() for row in f])
# -> [['a', '1', '1'],
['b', '1', '1'],
['c', '1', '1'],
['d', '1', '1'],
['e', '1', '1'],
['f', '1', '1']]
with open('somefile.txt', 'r') as f:
print([item for row in f for item in row.strip().split()])
# -> ['a', '1', '1', 'b', '1', '1', 'c', '1', '1', 'd', '1', '1', 'e', '1', '1', 'f', '1', '1']