我想在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=",")
答案 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())