This code below read .txt files and print the results, but I need save the results as .xlsx, I searched the internet but I didn't get any solution, can someone help me?
import os
path = input('Enter Directory:')
os.chdir(path)
def read_text_file(file_path):
with open(file_path, 'r') as f:
print(f.read())
for file in os.listdir():
if file.endswith(".txt"):
file_path = f"{path}\{file}"
read_text_file(file_path)
CodePudding user response:
Have a look at this library. It allows you to create excel files in python. This is one of the official examples and it is pretty straight-forward:
import xlsxwriter
workbook = xlsxwriter.Workbook('hello_world.xlsx')
worksheet = workbook.add_worksheet()
worksheet.write('A1', 'Hello world')
workbook.close()
CodePudding user response:
You can use pandas for this. It is very convenient for excel because you can build your columns and rows in pandas and then export them to excel.
Here is an example of how to store a Pandas Dataframe to Excel.
df1 = pd.DataFrame([['a', 'b'], ['c', 'd']],
index=['row 1', 'row 2'],
columns=['col 1', 'col 2'])
df1.to_excel("output.xlsx")