我有以下文件salida.txt
,在此示例中列数不同,只有2个。
cil HUF, M1 NSS,
442, 1123,
20140130, 2014012,
20140131, 2014014,
我想读取文件并将每列添加到新数组中。我不想这样:
['cli HUF', '442', '20140130', '20140131']
[' M1 NSS', '1123', '2014012', '2014014']
到目前为止我尝试过:
file = open('salida.txt', 'r')
for line in file:
// add them to the arrays
我遇到了处理数组数量的问题(它不总是2,取决于文件的列数),并从行中取出每个单词以添加到正确的数组中。如果我放入de loop print line[0]
,它会打印整行,我想逐字处理。
答案 0 :(得分:1)
删除最后一个逗号,然后在中心逗号中分割该行:
list1, list2 = [], []
file = open('salida.txt', 'r')
for line in file:
w1, w2 = line.strip(',').split(', ')
list1.append(w1)
list2.append(w2)
答案 1 :(得分:1)
你去了:
file = open('salida.txt', 'r')
lines = file.readlines()
file.close()
arrays = []
words = lines[0].split(",")
for i in range(0,len(words)):
arrays.append([words[i]])
for i in range(1,len(lines)):
words = lines[i].split(",")
for j in range(0,len(words)):
arrays[j].append(words[j])
答案 2 :(得分:1)
arrays = []
with open('salida.txt', 'r') as wordfile:
for line in wordfile:
# Split the line on commas.
words = line.split(',')
for count, word in enumerate(words):
# Remove any whitespace.
word = word.strip()
# That might leave a blank string, e.g. at the end.
if word:
# Do we need to add another array to our list of arrays?
if count == len(arrays):
arrays.append([])
arrays[count].append(word)
print arrays
答案 3 :(得分:1)
import csv
with open('salida.txt') as f:
whatYouWant = zip(*list(csv.reader(f)))[:-1]