pandas读取txt转存到excel
时间: 2023-08-05 12:04:37 浏览: 70
您可以使用`pandas`库来读取`.txt`文件,并将数据转存为`.xlsx`文件。以下是一个示例代码:
```python
import pandas as pd
# 读取txt文件
data = pd.read_csv('data.txt', delimiter='\t')
# 将数据保存为excel文件
data.to_excel('data.xlsx', index=False)
```
在上述代码中,我们首先使用`pd.read_csv`函数来读取`.txt`文件,通过设置`delimiter`参数来指定分隔符(例如制表符`\t`)。然后,我们使用`to_excel`函数将数据保存为`.xlsx`文件,通过设置`index`参数为`False`来避免写入行索引。
请确保将`data.txt`替换为您的`.txt`文件的路径,以及将`data.xlsx`替换为您想要保存的`.xlsx`文件的路径。
相关问题
python中txt文件转存为excel
可以使用Python中的pandas库来将txt文件转存为excel文件。以下是示例代码:
```python
import pandas as pd
# 读取txt文件
df = pd.read_csv("file.txt", sep="\t", header=None)
# 将数据存储为excel文件
df.to_excel("file.xlsx", index=False, header=False)
```
在代码中,我们首先使用`read_csv`函数读取txt文件,并指定了分隔符为制表符(`\t`),并且没有列名(`header=None`)。然后,我们使用`to_excel`函数将数据存储为excel文件,并指定了不将行索引和列名写入文件中。
你可以根据自己的需要修改代码中的文件路径和分隔符。
读取csv文件 指定列转存Excel文件
可以使用Python的pandas库来读取csv文件,并使用to_excel方法将指定列转存为Excel文件。以下是代码示例:
```python
import pandas as pd
# 读取csv文件
df = pd.read_csv('file.csv')
# 指定列转存为Excel文件
df[['列1', '列2', '列3']].to_excel('file.xlsx', index=False)
```
其中,'file.csv'是csv文件的路径,'列1'、'列2'和'列3'是要转存的列名,'file.xlsx'是要保存Excel文件的路径,index=False表示不包含行索引信息。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)