Reputation: 11
Hi i'm trying to convert .dat file to .csv file. But I have a problem with it. I have a file .dat which looks like(column name)
region GPS name ID stop1 stop2 stopname1 stopname2 time1 time2 stopgps1 stopgps2
it delimiter is a tab.
so I want to convert dat file to csv file. but the data keeps coming out in one column.
i try to that, using next code
import pandas as pd
with open('file.dat', 'r') as f:
df = pd.DataFrame([l.rstrip() for l in f.read().split()])
and
with open('file.dat', 'r') as input_file:
lines = input_file.readlines()
newLines = []
for line in lines:
newLine = line.strip('\t').split()
newLines.append(newLine)
with open('file.csv', 'w') as output_file:
file_writer = csv.writer(output_file)
file_writer.writerows(newLines)
But all the data is being expressed in one column. (i want to express 15 column, 80,000 row, but it look 1 column, 1,200,000 row) I want to convert this into a csv file with the original data structure. Where is a mistake?
Please help me... It's my first time dealing with data in Python.
Upvotes: 1
Views: 1728
Reputation: 833
If you're already using pandas, you can just use pd.read_csv()
with another delimiter:
df = pd.read_csv("file.dat", sep="\t")
df.to_csv("file.csv")
See also the documentation for read_csv and to_csv
Upvotes: 3