读取文件

读取txt文件内容信息

read():#读取整个文件信息

readline(): #读取一行数据信息

readlines():读取所有行的数据

txt 文件存有以下信息,用户名和密码,用户名和密码用豆号隔开,文件名user_info.txt

zhangshang,123
lisi,456
wangwu,789

user_file = open("user_info.txt","r")#打开文件
lines = user_life.readlins()#读取所有行的数据
user_file.close()#关闭文件
for line in lines:
  username = line.split(",")[0]#以豆号分隔,前部份索引为0,赋给username
  password = line.split(",")[1]#以豆号分隔,后部分索引为1,赋给password

输出结果:
zhangshang 123
lisi 456
wangwu 789

read 读取效果

----------------------------------------------------------------------------------------------------------

readline 读取效果

-----------------------------------------------------------------------------------------------------------

readline 读取效果

-------------------------------------------------------------------------------------------------

另外一种读取方式,这种不需要去关闭文件,跳出循环自动关闭
with open(r"C:\Users\Administrator\Desktop\1.txt","r") as f: f1 = f.read() for i in f1: print i

读取JSON文件

普通取值
import
json fp = open("../dd/login.json") data = json.load(fp)#加载fp print data["login1"] #键取值
封装成函数

class OperetionJson(): #读取json 文件 def read_data(self): # fp = open("../dd/login.json") # fp.close() with open("../dd/login.json") as fp: data = json.load(fp) return data #根据关键字获取数据 def get_data(self,id): return self.data[id] if __name__ == '__main__': opjson = OperetionJson() print opjson.get_data("login2")

读取excel文件

import xlrd
date = xlrd.open_workbook(r"G:\untitled1\dd\interface.xlsx","wd")
tables = date.sheets()[0]#通过获得第一个sheets 的所有内容
print tables.nrows
print tables.cell_value(2,3)#拿到第二行第三列第一行,第一列都是0开始
读取excel封装成函数
class OperationExcel():
    def __init__(self,file_name=None,sheet_id=None):
        if file_name:
            self.file_name=file_name
            self.sheet_id=sheet_id
            self.data=self.get_data()
        else:
            self.file_name=r"G:\untitled1\dd\interface.xlsx"
            self.sheet_id = 0
            self.data = sheet_id.get_data()
    #获取sheets的内容
    def get_data(self,file_name,sheet_id):
        data=xlrd.open_workbook(file_name)
        tables = data.sheets()[sheet_id]
        return tables
    #获取行数
    def get_lines(self):
        tables = self.data
        return tables.nrows
    #获取某个单元格的内容
    def get_cell_value(self,row,col):
        return self.data.get_get_cell_value(row,col)


if __name__ == '__main__':
    opers = OperationExcel()
    print opers.get_data()
    print opers.get_cell_value(2,2)

 

posted @ 2018-02-27 15:02  藤上小冬瓜  阅读(268)  评论(0编辑  收藏  举报