简体   繁体   中英

How to save python result as excel xlsx

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)

the data format in.txt files is like this:

"174125_1.jpg" 
"174127_1.jpg" 
"174128_1.jpg" 
"174129_1.jpg" 
"174130_1.jpg" 
"176475_1.jpg" 
"178836_1.jpg" 
"179026_1.jpg" 
"179026_2.jpg" 
"179026_3.jpg" 
"179026_4.jpg" 
"179026_5.jpg" 

them are registration data from images uploaded to an e-commerce.

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")  

Thanks for your help, but how can I apply xlsxwriter in my code? I'm a begginer in python. I wrote that way, but didn't work as expected:

import os
import xlsxwriter

path = input('Enter Directory:')

workbook = xlsxwriter.Workbook('SKUs Cadastrados123.xlsx')
worksheet = workbook.add_worksheet()

os.chdir(path)


def read_text_file(file_path):
    with open(file_path, 'r') as f:
        worksheet.write('A1', f.read())


for file in os.listdir():
    if file.endswith(".txt"):
        file_path = f"{path}\{file}"
        read_text_file(file_path)

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM