我试图将两个列表合并到一个csv中,并让它为第二个列表的每一行输出一行。
a.csv
1
2
3
b.csv
a,x
b,y
c,z
输出:
c.csv
1|a|x
2|a|x
3|a|x
1|b|y
2|b|y
3|b|y
1|c|z
2|c|z
3|c|z
因此对于每一行" a"合并" b"的每一行,并在" c"中获取一个列表。
注意,我没有必要分开" b"重新排序列,保持原始顺序 似乎需要一个循环,但我没有运气这样做。
回答(输出不完美,但我需要的确定):
import csv
from itertools import product
def main():
with open('a.csv', 'rb') as f1, open('b.csv', 'rb') as f2:
reader1 = csv.reader(f1, dialect=csv.excel_tab)
reader2 = csv.reader(f2, dialect=csv.excel_tab)
with open('output.csv', 'wb') as output:
writer = csv.writer(output, delimiter='|', dialect=csv.excel_tab)
writer.writerows(row1 + row2 for row1, row2 in product(reader1, reader2))
if __name__ == "__main__":
main()
输出文件:
1|a,x
1|b,y
1|c,z
2|a,x
2|b,y
2|c,z
3|a,x
3|b,y
3|c,z
是" |"只是其中一个分隔符 很高兴知道如何获得" 1 | a | x"等等。
答案 0 :(得分:0)
一种方法是使用pandas
:
import pandas as pd
df = pd.concat([pd.read_csv(f, header=None) for f in ('a.csv', 'b.csv')], axis=1)
df.to_csv('out.csv', sep='|', index=False, header=False)
答案 1 :(得分:0)
使用itertools.product
的本机Python方法:
from itertools import product
#read file a, remove newline, replace commas with new delimiter and ignore empty lines
a = [line[:-2].strip().replace(",", "|") for line in open("a.csv", "r") if line[:-2].strip()]
#read file b, leave newline in string
b = [line.replace(",", "|") for line in open("b.csv", "r") if line[:-2].strip()]
#combine the two lists
c = ["|".join([i, j]) for i, j in product(a, b)]
#write into a new file
with open("c.csv", "w") as f:
for item in c:
f.write(item)
#output
1|a|x
1|b|y
1|c|z
2|a|x
2|b|y
2|c|z
3|a|x
3|b|y
3|c|z