Linux服务器中有2个txt文件。 第一个数据文件:
a;1234
b;12334
c;234234
第二个数据文件:
a ; ass ; asfda
b ; sdfq; qwrwffsaa
c ; asda ; qdasasd
我尝试使用 python 创建一个有 2 张表的 Excel 文件。 第一张表保留第一个数据文件,第二张表应保留第二个数据文件。
到目前为止我开发的是:
#!/bin/python
import xlsxwriter
import smtplib
import datetime
now = datetime.datetime.now()
workbookname = 'Excel_'+now.strftime("%Y-%m-%d_%H:%M")+'.xlsx'
workbook = xlsxwriter.Workbook(workbookname)
worksheet = workbook.add_worksheet('Sheet1')
worksheet.write('A1', 'Hostname')
worksheet.write('B1', 'User Name')
worksheet2 = workbook.add_worksheet('User Privilege')
worksheet2.write('A1', 'Hostname')
worksheet2.write('B1', 'User Detail')
worksheet2.write('C1', 'Description')
with open('/tmp/file1.txt') as f:
content = f.read().splitlines()
i = 0
while i < len(content):
content2 = content[i].split(';')
worksheet.write('A'+str(i+2), content2[0])
worksheet.write('B'+str(i+2), content2[1])
workbook.close()
i = 0
while i < len(content):
with open('/tmp/file2.txt') as f:
content = f.read().splitlines()
worksheet2.write('A' + str(i + 2), content2[0])
worksheet2.write('B' + str(i + 2), content2[1])
worksheet2.write('C' + str(i + 2), content2[2])
i=i+1
workbook.close()
此脚本仅适用于第一个工作表,它不能写入第二个工作表。
最佳答案
使用pandas
,这可以在几行内完成
import pandas
df1 = pandas.read_csv('file1.csv', sep = ';', header = None)
df2 = pandas.read_csv('file2.csv', sep = ';', header = None)
writer = pandas.ExcelWriter('output.xlsx')
df1.to_excel(writer, 'sheet 1')
df2.to_excel(writer, 'sheet 2')
writer.save()
关于python - 使用 Python 从 Linux 中的不同文件创建 Excel 工作表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53802104/