我想使用csv.reader
编写Python3代码。
这是一个示例文件。
#hoge.txt
a b c d e f g
a b c d e f g
a b c d e f g
a b c d e f g
我想要这样的数组
[[a,a,a,a],[b,b,b,b],[c,c,c,c]...[g,g,g,g]]
(元素数量是固定的。)
我当前的代码是
from csv import reader
with open('hoge.txt') as f:
data = reader(f, delimiter=' ')
但是,显然,它不起作用。 我怎样才能做到
data = reader(f, delimiter='\s+')
答案 0 :(得分:3)
with open('hoge.txt', 'r') as fin:
data=[line.split() for line in fin]
这将给出类似
的输出[['a', 'b', 'c', 'd', 'e', 'f', 'g'], ['a', 'b', 'c', 'd', 'e', 'f', 'g'],
['a', 'b', 'c', 'd', 'e', 'f', 'g'], ['a', 'b', 'c', 'd', 'e', 'f', 'g']]
但是由于您想要的输出不同
list1 = []
for i in range(0,len(data)):
list1.append([x[i] for x in data])
这会产生
[['a', 'a', 'a', 'a'], ['b', 'b', 'b', 'b'], ['c', 'c', 'c', 'c'], ['d', 'd', 'd', 'd']]
希望它能解决您的问题。
答案 1 :(得分:1)
确定要获取CSV吗?您的示例文件是用空格分隔的,而我的第一种方法是使用split()。像这样:
allcols = []
with open("hoge.txt", "r") as f:
vals = f.read().split()
for i, el in enumerate(vals):
allcols[i].append(el)
如果您确实有CSV格式但有多余的空格,那么我仍然会进行每行处理,但是像这样:
from csv import reader
data = ""
with open("hoge.txt", "r") as f:
newline = f.read().strip(" ")
data.append(reader(newline))
hth