1. 程式人生 > >python下讀取檔案到列表(txt,csv, excel)

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