如何使用Python将.dat转换为.csv?数据在一列中表达

发布于 2025-01-21 11:43:26 字数 851 浏览 3 评论 0原文

嗨,我正在尝试将.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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情话难免假 2025-01-28 11:43:26

如果您已经在使用pandas,则可以与另一个定界符一起使用pd._read_csv()

df = pd.read_csv("file.dat", sep="\t")
df.to_csv("file.csv")

另请参见 read_csv to_csv

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文