简体   繁体   English

Pandas 将文本文件转换为 CSV

[英]Pandas converting Text file to CSV

I need to convert a text file to CSV.我需要将文本文件转换为 CSV。 Please see my code below.请在下面查看我的代码。 My text file contains 5 columns separated by unequal spaces.我的文本文件包含由不等空格分隔的 5 列。 When I converted this to a CSV file, all these 5 columns are coming in a single column in the Excel file.当我将其转换为 CSV 文件时,所有这 5 列都在 Excel 文件中的一个列中。

Code:代码:

import pandas as pd   
 
dataframe1 = pd.read_csv("C:\HARI_BKUP\PYTHON_SELF_Learning\Funct_Noise_Corners_2p0_A.txt",) 
  
dataframe1.to_csv('FF.csv', index = None)

I need a CSV file with each separate column.我需要一个包含每个单独列的 CSV 文件。 May I know where I went wrong?我可以知道我哪里出错了吗?

TEXT FILE文本文件

在此处输入图像描述

Output after running the code Output 运行代码后

dataframe1 = pd.read_csv("C:\HARI_BKUP\PYTHON _SELF Learning\Funct_Noise_Corners_2p0_A.txt", sep="\t")

在此处输入图像描述

I think this will solve it我认为这会解决它

dataframe1 = pd.read_csv('textfile.txt', delimiter = "\t")

or或者

dataframe1 = pd.read_csv('textfile.txt', sep=" ")

When you read the file, you didn't specify the separator.当您阅读文件时,您没有指定分隔符。 Therefore, Python thinks that the separators are commas and treats the input as a CSV file (you can check the docs .).因此,Python 认为分隔符是逗号,并将输入视为 CSV 文件(您可以查看文档。)。

However, your input seems to be a space-separated file instead.但是,您的输入似乎是一个以空格分隔的文件。 Your code should be:您的代码应该是:

import pandas as pd

file_path = "C:\HARI_BKUP\PYTHON_SELF_Learning\Funct_Noise_Corners_2p0_A.txt"
dataframe1 = pd.read_csv(file_path, delim_whitespace=True)

dataframe1.to_csv('FF.csv', index = None)

Simply set the parameter delim_whitespace=True would make it work for you.只需设置参数delim_whitespace=True使其为您工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM