3

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.

2 Answers2

1

Have a look at this library. It allows you to create excel files in python. Edit: Your example is pretty straight-forward:

def read_text_file(file_path):
    with open(file_path, 'r') as f:
        i = 0
        for line in f:
           # Write to xlsx using row, column syntax
           worksheet.write(i, 0, line)
           i += 1
Josip Domazet
  • 2,246
  • 2
  • 14
  • 37
1

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

Edit:

Now that I know, what you are trying to do I can say with confidence, pandas is the library you want to use.

Using pandas, your whole code can be reduced to 3 lines:

import pandas as pd

df = pd.read_csv('input.txt', names=["pictures"])
df.to_excel('output.xlsx')

Also if you intend to use python for data-driven tasks. Pandas is the best library for that kind of stuff and I highly recommend you learn it.

Raavgo
  • 323
  • 3
  • 15