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

Python读取txt、csv和excel文件到列表教程
本文介绍了如何使用Python分别读取txt、csv和excel文件的内容,并将其加载到列表中,便于数据处理。从txt文件的简单读取,到csv文件的pandas操作,再到excel文件的openpyxl库应用,详细讲解了每个步骤。

读取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

 

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

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值