python读取txt、csv和excel文件

1、python读取txt文件:(思路:先打开文件,读取文件,最后用for循环输出内容)python

fp = open('test.txt','r')excel

lines = fp.readlines()it

fp.close()自动化

for line in lines:for循环

    username = line.split(',')[0]table

    password = line.split(',')[1]test

注:第一句是以只读方式打开文本文件;第二个是读取全部行的数据(read:读取整个文件;readline:读取一行数据);最后必定要关闭文件。最终会返回一个列表,经过for循环能够一个个的读取其中的数据。如username,password。这时候经过split方法进行分割,最终能够获得username    password,这样就能够在自动化里面作参数化了。import

2、python读取CSV文件date

import csv
date =csv.reader(open('test.csv','r'))
for test in date:
    print test循环

    print test[0]

注:须要先导入csv包,而后经过reader方法读取内容,最终会返回一个列表。想选择某一列数据,只须要制定列表下标便可

3、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)

注:(0,2)表示第二行第三列的数据,也就是:备注

(未完,待续)

相关文章
相关标签/搜索