python下读取文件到列表(txt,csv, excel)

读取txt 数据

#读取txt数据  filepath = "sample1.txt"
def data_read(filepath):
    fp = open(filepath, "r")
    datas = []#存储处理后的数据
    lines = fp.readlines()#读取整个文件数据
    i = 0# 为一行数据
    for line in lines: 
        row = line.strip('\n').split()#去除两头的换行符,按空格分割
        datas.append(row)        
        i = i + 1
        print("读取第", i,"行")   
                    
    fp.close()    
    return datas

读取csv文件

import codecs
from itertools import islice
def loadData(filename):
    file = codecs.open(filename, 'r', 'utf-8')
    data = []
    for line in islice(file, 1, None): #islice对迭代器做切片
        line = line.strip().split(',')
        print ('读取数据中.....')
        data.append(line)
     return data

读取excel文件

import  xlrd

file_path = 'data/sound_self_sample.xlsx'
data = xlrd.open_workbook(file_path)    #open the excel file
table  = data.sheets()[0]   #open the first sheet
row_n = table.nrows
for i in range(1, row_n):
    print(table.row_values(i)) #print the ith line

 

紫薯啊,你真的能抗衰老吗

 

你可能感兴趣的:(Python)