读取一个文件并用每列的单词创建数组

2024-05-23 19:26:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的文件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]放在里面,它会打印出整行,我想逐字处理它。你知道吗


Tags: 文件txtforcliline数组open例子
3条回答
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

去掉最后一个逗号,然后将中间的逗号分隔开:

list1, list2 = [], []
file = open('salida.txt', 'r')
for line in file:
    w1, w2 = line.strip(',').split(', ')
    list1.append(w1)
    list2.append(w2)
import csv

with open('salida.txt') as f:
    whatYouWant = zip(*list(csv.reader(f)))[:-1]

相关问题 更多 >