行之间无空行十分重要,如果有空行或者数据集中行末有空格,读取数据时一般会出错,引发[list index out of range]错误。PS:已经被这个错误坑过很多次!
使用python I/O写入和读取CSV文件
使用PythonI/O写入csv文件
以下是将"birthweight.dat"低出生体重的dat文件从作者源处下载下来,并且将其处理后保存到csv文件中的代码。
import csv
import os
import numpy as np
import random
import requests
# name of data file
# 数据集名称
birth_weight_file = 'birth_weight.csv'
# download data and create data file if file does not exist in current directory
# 如果当前文件夹下没有birth_weight.csv数据集则下载dat文件并生成csv文件
if not os.path.exists(birth_weight_file):
birthdata_url = 'https://github.com/nfmcclure/tensorflow_cookbook/raw/master/01_Introduction/07_Working_with_Data_Sources/birthweight_data/birthweight.dat'
birth_file = requests.get(birthdata_url)
birth_data = birth_file.text.split(' ')
# split分割函数,以一行作为分割函数