如何使用python将数据从txt文件转换为Excel文件

如何使用python将数据从txt文件转换为Excel文件

本文介绍了如何使用python将数据从txt文件转换为Excel文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,其中包含

您可以看到您的数据已移动一列,而您的索引轴已保留.如果你不想要这个索引列(因为你没有为你的 df 分配一个索引,所以它有熊猫提供的任意一个):

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

您的输出将如下所示:

在这里您可以看到索引已从 excel 文件中删除.

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:

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:

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

这篇关于如何使用python将数据从txt文件转换为Excel文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 15:31