将.data文件写入或转换为csv

时间:2019-09-21 23:22:45

标签: python csv

我想在python中将.data文件转换为.csv。基本上,我想将此.data文件作为csv文件导出到我的工作目录中。

url = "https://archive.ics.uci.edu/ml/machine-learning-databases/spambase/spambase.data"
raw_data = urllib.urlopen(url)
mydataset = np.loadtxt(raw_data, delimiter=",")

1 个答案:

答案 0 :(得分:1)

请参考此答案 Dump a NumPy array into a csv file

我也认为您不需要以numpy数组加载数据,因为它已经是csv格式。您可以只将原始数据写入.csv文件中。

with open('csv_file.csv', 'wb') as file:
    file.write(raw_data.read())

足够了。

所以总结一下,如果要使用numpy编写csv,则

import urllib.request as urllib
import numpy as np

url = "https://archive.ics.uci.edu/ml/machine-learning-databases/spambase/spambase.data"
raw_data = urllib.urlopen(url)
mydataset = np.loadtxt(raw_data, delimiter=",")
np.savetxt("foo.csv", mydataset, delimiter=",")

更简单,更快捷的是只写入原始数据

import urllib.request as urllib
import numpy as np

url = "https://archive.ics.uci.edu/ml/machine-learning-databases/spambase/spambase.data"
raw_data = urllib.urlopen(url)
with open('csv_file.csv', 'wb') as file:
    file.write(raw_data.read())