I try to export 2 specific lines from multiple (.txt) files in path as excel rows, and exporting them into excel files.. But the (.xlsx) file just containing first row (just exported lines of one text file).
import pandas as pd
import linecache
import xlsxwriter as xlsw
import os
import glob
directory=('C:\Users\john\Desktop')
os.chdir(directory)
files=glob.glob('*.txt')
for filename in files:
name = linecache.getline(filename,5)
id = linecache.getline(filename,13)
info = [name,id]
final_list = []
for i in info:
final_list.append(i.strip())
print (final_list)
df = pd.DataFrame(final_list)
df = df.transpose()
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='welcome',startrow=1,startcol=0, header=False, index=False)
writer.save()
CodePudding user response:
Use:
import pandas as pd
import linecache
import xlsxwriter as xlsw
import os
import glob
directory=('test')
os.chdir(directory)
files=glob.glob('*.txt')
final_list = []
for filename in files:
name = linecache.getline(filename,5)
id = linecache.getline(filename,13)
info = [name,id]
final_list.append([i.strip() for i in info])
print (final_list)
df = pd.DataFrame(final_list)
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='welcome',startrow=1,startcol=0, header=False, index=False)
writer.save()