close

How to convert data from txt files to Excel files using python

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to convert data from txt files to Excel files using python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to convert data from txt files to Excel files using python?

  1. How to convert data from txt files to Excel files using python?

    You do not need python! Just rename your text file to CSV and voila, you get your desired output 🙂

  2. convert data from txt files to Excel files using python

    You do not need python! Just rename your text file to CSV and voila, you get your desired output 🙂

Method 1

The pandas library is wonderful for reading csv files (which is the file content in the image you linked). You can read in a csv or a txt file using the pandas library and output this to excel in 3 simple lines.

import pandas as pd

df = pd.read_csv('input.csv') # if your file is comma separated

or if your file is tab delimited '\t':

df = pd.read_csv('input.csv', sep='\t')

To save to excel file add the following:

df.to_excel('output.xlsx', 'Sheet1')

complete code:

import pandas as pd
df = pd.read_csv('input.csv') # can replace with df = pd.read_table('input.txt') for '\t'
df.to_excel('output.xlsx', 'Sheet1')

This will explicitly keep the index, so if your input file was:

A,B,C
1,2,3
4,5,6
7,8,9

Your output excel would look like this:

index excel example

You can see your data has been shifted one column and your index axis has been kept. If you do not want this index column (because you have not assigned your df an index so it has the arbitrary one provided by pandas):

df.to_excel('output.xlsx', 'Sheet1', index=False)

Your output will look like:

output excel no index

Here you can see the index has been dropped from the excel file.

Method 2

You do not need python! Just rename your text file to CSV and voila, you get your desired output 🙂

If you want to rename using python then – You can use os.rename function

os.rename(src, dst)

Where src is the source file and dst is the destination file

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read