python csv文件放到哪里

Python011

python csv文件放到哪里,第1张

使用Python的csv模块csv模块中的函数reader(csvfile, dialect='excel', **fmtparams)11参数说明: csvfile,必须是支持迭代(Iterator)的对象,可以是文件(file)对象或者列表(list)对象,如果是文件对 象,打开时需要加”b”标志参数。dialect,编码风格,默认为excel的风格,也就是用逗号(,)分隔,dialect方式也支持自定义,通过调用register_dialect方法来注册,下文会提到。fmtparam,格式化参数,用来覆盖之前dialect对象指定的编码风格。加载文件代码:import csv def loadCSVfile1():list_file = []with open('train.csv','rb') as csv_file:all_lines=cvs.reader(csv_file)for one_line in all_lines:list_file.append(one_line)list_file.remove(list_file[0])arr_file = array(list_file)label = arr_file[:, 0]data = arr_file[:, 1:]return data, label 123456789101112123456789101112加载csv核心部分还是 其中,‘rb’中的r表示“读”模式,因为是文件对象,所以加‘b’。open()返回了一个文件对象 myFile,reader(myFile)只传入了第一个参数,另外两个参数采用缺省值,即以excel风格读入。reader()返回一个 reader对象all_lines,all_lines是一个list,当调用它的方法lines.next()时,会返回一个string。上面程序的效果是将csv 文件中的文本按行打印,每一行的元素都是以逗号分隔符’,’分隔得来。

使用 python list即可,因为list可以加入不同的数据类型的数据。

results = list()

lines = open('cvs_file', 'r').readlines()

for line in lines:

    elements = line.strip().split(',') # supposed limiter is ','

    for e in elements:

        try:

            results.append(float(e))

        except:

            continue

# Here results will contains all splitted elements

# all elements are string read from cvs file, so you need to

# converse it with float operator. But if element is read string

# we can catch conversion exception and throw it anyway.