使用Python将数据写入2个文件的excel中

问题描述:

我有两个文件有diff数据。我想用python写成excel。 我给了定义4列标题。使用Python将数据写入2个文件的excel中

下面是片段。我想要俱乐部,所以我不必定义行和列两次。 ABC.txt和LMN.txt都有数据要写入xlsx。

row=1 
    col=0 
    with open('ABC.txt','r') as f: 
     for K in f: 
      worksheet.write(row,col,K) 
      row+=1 
    row=1 
    col=0 
    with open('LMN.txt','r') as f: 
     for X in f: 
      worksheet.write_url(row , col+1, X) 
      row += 1 

     workbook.close() 

你真的应该考虑使用像Pandas这样的软件包。这种类型的事情是可笑容易在大熊猫:

import pandas as pd 

df = pd.DataFrame(columns=['col1', 'col2']) 

df['col1'] = ['hello1', 'world1'] 
df['col2'] = ['hello2', 'world2'] 
print df 

df.to_excel('output.xls', index=False) 

输出:

 col1 col2 
0 hello1 hello2 
1 world1 world2 

注意,列可以作为数组进行传递,这样你就可以建立自己的阵列,只要你喜欢,然后把它们放入列。

编辑:

如果你不能使用熊猫(或不会,因为某些原因),你可以使用一个低技术的解决方案,如荏苒。假设你可以得到所有你列的准备好了,你可以用好老荏苒把它们转化为行:

col1 = ['hello1', 'world1', 'again1'] 
col2 = ['hello2', 'world2', 'again2'] 
col3 = ['hello3', 'world3', 'again3'] 

out = '' 
for row in zip(col1, col2, col3): 
    out += ','.join(row) + '\n' 
print out 

输出:

hello1,hello2,hello3 
world1,world2,world3 
again1,again2,again3 

然后,你可以写到一个文件,说带有csv扩展名,可由excel读取。

+0

看起来很有趣。但看起来像我不能使用Panda按照我的代码和广泛的目的。但我一定会试一试。 – RishuA

+0

我添加了另一个解决方案,不使用熊猫,但请记住,您需要在内存中拥有所有这些数据。 – Shovalt

如果文件过大,可以先阅读它们的结构结合在一起,然后在一个循环中写出来:

with open('ABC.txt', 'r') as f: 
    cola = list(f) 

with open('LMN.txt', 'r') as f: 
    colb = list(f) 

rows = zip(cola, colb) 

for idx, row in enumerate(rows): 
    worksheet.write(idx, 0, row[0]) 
    worksheet.write_url(idx, 1, row[1]) 
+0

其实第一个文件已经有数据了。对于第二个我必须创建它,同时我的代码输出(multilpe)将被写入,并且最后第一个文件数据和第二个文件中生成的数据将在xlsx文件中以列和行组合在一起由第二过程创建。你的想法也很好,今天我会尝试。 – RishuA