Pandas converting Text file to CSV

Viewed 4029

I need to convert a text file to CSV. Please see my code below. My text file contains 5 columns separated by unequal spaces. When I converted this to a CSV file, all these 5 columns are coming in a single column in the Excel file.

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. May I know where I went wrong?

TEXT FILE

enter image description here

Output after running the code

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

enter image description here

2 Answers

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.).

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.

I think this will solve it

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

or

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