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
Output after running the code
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 .).
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.
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.