简体   繁体   中英

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

I have a text file that contains data like this . It is is just a small example, but the real one is pretty similar.

I am wondering how to display such data in an "Excel Table" like this using Python?

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:

索引excel示例

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:

输出excel没有索引

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

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

XLWT

I use the XLWT library. It produces native Excel files, which is much better than simply importing text files as CSV files. It is a bit of work, but provides most key Excel features, including setting column widths, cell colors, cell formatting, etc.

保存这是:

df.to_excel("testfile.xlsx")

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