我正在尝试使用包含两个文件之间映射的 keyfile.csv 将 file1.csv 文件中的值写入 file2.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 应该会解决这个问题,但那并没有发生。我做错了什么?
请您参考如下方法:
你有两个问题。
- 您应该只读取一次 key 文件并根据映射构建字典
- 您需要在输出文件的每一行末尾写一个
\n
