使用Python将csv文件中的多个列复制到现有的xls文件中

我对Python很新,但是在开始这个过程中遇到了一些困难。 我正在使用Python 3。

我GOOGLE了,发现不lesspython模块,帮助这个,但希望在这里更定义的答案。 所以基本上,我需要从csv文件读取某些列,即G,H,I,K和M.我需要的不是连续的。

我需要从csv文件中读取这些列,并将它们转移到已有数据中已有数据的空列中。

我查找了openpyxl,但它似乎不能用于csv / xls文件,只有xlsx。 我可以使用xlwt模块来做到这一点吗?

任何指导哪个模块可能最适合我的用例将不胜感激。 同时,我要用xlwt / xlrd修补。

我build议使用pandas。 它具有读写csv和xls文件的方便function。

import pandas as pd from openpyxl import load_workbook #read the csv file df_1 = pd.read_csv('c:/test/test.csv') #lets say df_1 has columns colA and colB print(df_1) #read the xls(x) file df_2=pd.read_excel('c:/test/test.xlsx') #lets say df_2 has columns aa and bb #now add a column from df_1 to df_2 df_2['colA']=df_1['colA'] #save the combined output writer = pd.ExcelWriter('c:/test/combined.xlsx') df_2.to_excel(writer) writer.save() #alternatively, if you want to add just one column to an existing xlsx file: #ie get colA from df_1 into a new dataframe df_3=pd.DataFrame(df_1['colA']) #create writer using openpyxl engine writer = pd.ExcelWriter('c:/test/combined.xlsx', engine='openpyxl') #need this workaround to provide a list of work sheets in the file book = load_workbook('c:/test/combined.xlsx') writer.book = book writer.sheets = dict((ws.title, ws) for ws in book.worksheets) column_to_write=16 #this would go to column Q (zero based index) writeRowIndex=0 #don't plot row index sheetName='Sheet1' #which sheet to write on #now write the single column df_3 to the file df_3.to_excel(writer, sheet_name=sheetName, columns =['colA'],startcol=column_to_write,index=writeRowIndex) writer.save() 

您可以尝试XlsxWriter,这是用于编写Excel 2007+ XLSX文件格式的全functionPython模块。 https://pypi.python.org/pypi/XlsxWriter