如何使用Python将.dat转换为.csv?数据在一列中表达
嗨,我正在尝试将.dat文件转换为.csv文件。 但是我有问题。 我有一个看起来像(列名)的文件.DAT
region GPS name ID stop1 stop2 stopname1 stopname2 time1 time2 stopgps1 stopgps2
它是一个选项卡。
因此,我想将DAT文件转换为CSV文件。 但是数据不断出现在一列中。
我尝试使用下一个代码
import pandas as pd
with open('file.dat', 'r') as f:
df = pd.DataFrame([l.rstrip() for l in f.read().split()])
,
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)
但是所有数据都在一列中表示。 (我想表达15列,80,000行,但看起来1列,1,200,000行) 我想将其转换为具有原始数据结构的CSV文件。 在哪里错误?
请帮助我...这是我第一次处理Python的数据。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您已经在使用pandas,则可以与另一个定界符一起使用
pd._read_csv()
:另请参见 read_csv 和 to_csv
If you're already using pandas, you can just use
pd.read_csv()
with another delimiter:See also the documentation for read_csv and to_csv