无法写入Python中.csv文件中的所有行?

时间:2015-08-20 14:07:00

标签: python csv

我尝试使用keyfile.csv通过file2.csv文件中的值写入file1.csv文件,其中包含两个文件之间的映射,因为这两个文件没有相同的列顺序。

def convert():

    Keyfile = open('keyfile.csv', 'rb')
    file1 = open('file1.csv', 'rb')
    file2 = open('file2.csv', 'w')

    reader_Keyfile = csv.reader(Keyfile, delimiter=",")
    reader_file1 = csv.reader(file1, delimiter=",")
    writer_file2 = csv.writer(file2, delimiter=",")
    for row_file1 in reader_file1:
        for row_Keyfile in reader_Keyfile:
            for index_val in row_Keyfile:
                file2.write(row_file1[int(index_val)-1]+',')
    # Closing all the files     
    file2.close()
    Keyfile.close()
    file1.close()

# keyfile structure: 3,77,65,78,1,10,8...
# so 1st column of file2 is 3rd column of file1 ; 
# col2 of file 2 is col77 of file1 and so on

我只能在file2.csv中只写一行。它应该与file1.csv中的行数一样多。如何在一行完成后移动到下一行?我假设Loop应该处理这个但是没有发生。我做错了什么?

3 个答案:

答案 0 :(得分:3)

你有两个问题。

  1. 您应该只读取一次密钥文件并从映射中构建一个字典
  2. 您需要在输出文件的每一行末尾写一个\n

答案 1 :(得分:3)

我假设KeyFile只是一行,给出了所有行的映射。以下内容应该有效:

def convert():
    with open('keyfile.csv') as Keyfile, open('file1.csv', 'r') as file1, open('file2.csv', 'wb') as file2:
        mappings = next(csv.reader(Keyfile, delimiter=","))
        mappings = [int(x)-1 if x else None for x in mappings]

        reader_file1 = csv.reader(file1, delimiter=",")
        writer_file2 = csv.writer(file2, delimiter=",")

        for row_file1 in reader_file1:
            row = [''] * len(mappings)
            for from_index, to_index in enumerate(mappings):
                if to_index != None:
                    row[to_index] = row_file1[from_index]
            writer_file2.writerow(row)

它假设列映射从1开始。

答案 2 :(得分:2)

正如其他人提到的那样,嵌套循环是有问题的。相反,在行迭代之外创建映射,然后根据映射写入行。我为此使用dict对象。

import csv

Keyfile = open('keyfile.csv', 'rb')
file_out = csv.reader(open('file1.csv', 'rb'), delimiter=",")
file_in = csv.writer(open('file2.csv', 'w'), delimiter=",")

mapDict = {}

# the first line in KeyFile convert to dict
reader = csv.reader(Keyfile, delimiter=',')
for i, v in enumerate(reader.next()):
    if v != ' ':
        mapDict[i] = int(v)


# re-index the row in file_in based on mapDict
for row in file_out:
    file_in.writerow([row[c] for c in mapDict.values()])