您的位置:首页 > 编程语言 > Python开发

python-读取excel,txt,csv文件

2018-02-11 11:47 781 查看
一、python读取txt文件:(思路:先打开文件,读取文件,最后用for循环输出内容)
fp = open('test.txt','r')
lines = fp.readlines()
fp.close()
for line in lines:
    username = line.split(',')[0]
    password = line.split(',')[1]
注:第一句是以只读方式打开文本文件;第二个是读取所有行的数据(read:读取整个文件;readline:读取一行数据);最后一定要关闭文件。最终会返回一个列表,通过for循环可以一个个的读取其中的数据。如username,password。这时候通过split方法进行分割,最终可以得到username    password,这样就可以在自动化里面做参数化了。

二、python读取CSV文件
import csv
date =csv.reader(open('test.csv','r'))
for test in date:
    print test
    print test[0]
注:需要先导入csv包,然后通过reader方法读取内容,最终会返回一个列表。想选择某一列数据,只需要制定列表下标即可

三、python读取excel
需要先安装xlrd模块
import xlrd
book=xlrd.open_workbook(data_dirs()+'/system.xlsx')
sheet=book.sheet_by_index(0)
print sheet.cell_value(0,2)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: