zhangwuxuan

前言

小伙伴们在使用python做接口自动化测试的时候,需要创建数据文件进行参数化,那么Python如何读取和写入txt,csv的文件数据呢?今天我们一起来学习一下吧!

一:读取txt文件数据

(1)创建txt数据文件,创建好文件记得要关闭文件,不然读取不了文件内容

(2)打开PyCharm,,创建python file ,写入以下代码

#读取txt文件
file=open("G:\\info.txt",\'r\',encoding=\'utf-8\')
userlines=file.readlines()
file.close()
for line in userlines:
    username=line.split(\',\')[0] #读取用户名
    password=line.split(\',\')[1] #读取密码
    print(username,password)

(3)运行后的结果如下

二:读取csv文件数据

(1)创建txt数据文件,创建好文件要关闭该文件,不然读取不文件内容

注:先创建txt的文件,然后另存为csv后缀文件

(2)打开PyCharm,,创建python file ,写入以下代码

#读取csv文件
import csv
file="G:\\info.csv"
filename=open(file)
reader=csv.reader(filename)
for row in reader:
     print("用户名:%s"%row[0],"密码:%s"%row[1])  #数组下标是以0开始的

(3)运行后的结果如下

三:写入数据到txt文件

(1)打开PyCharm,,创建python file ,写入以下代码

import random
import string#--------写入txt文件
#生成小写字母和数字的混合字符串
# all_string=[\'0\', \'1\', \'2\', \'3\', \'4\', \'5\', \'6\', \'7\', \'8\', \'9\', \'z\', \'y\', \'x\', \'w)\', \'v\', \'u\', \'t\', \'s\', \'r\', \'q\', \'p\', \'o\',
#             \'n\', \'m\', \'l\', \'k\', \'j\', \'i\', \'h\', \'g\', \'f\', \'e\', \'d\', \'c\', \'b\', \'a\']
#生成大小字母和数字一起的大字符串
all_str = string.ascii_letters + string.digits
for i in range(1,11): #生成10个账号
    username= \'\'.join(random.sample(all_str,5))+\'@163.com\'
    password = random.randint(10000, 99999)
    x = str(username) +\'\' + str(password) + \'\n\'
    with open("G:\\user.txt", "a") as f:
        f.write(x)
    print(u"生成第[%d]个账号"%(i))

(2)运行后的结果如下

生成txt文件

三:写入数据到csv文件

(1)打开PyCharm,,创建python file ,写入以下代码

import random
import string
import csv#--------写入csv文件
#生成小写字母和数字的混合字符串
# all_string=[\'0\', \'1\', \'2\', \'3\', \'4\', \'5\', \'6\', \'7\', \'8\', \'9\', \'z\', \'y\', \'x\', \'w)\', \'v\', \'u\', \'t\', \'s\', \'r\', \'q\', \'p\', \'o\',
#             \'n\', \'m\', \'l\', \'k\', \'j\', \'i\', \'h\', \'g\', \'f\', \'e\', \'d\', \'c\', \'b\', \'a\']
#生成大小字母和数字一起的大字符串
all_str = string.ascii_letters + string.digits
for i in range(1,11): #生成10个账号
    username= \'\'.join(random.sample(all_str,5))+\'@163.com\'
    password = random.randint(10000, 99999)
    x = str(username) +\'\' + str(password) + \'\n\'
    with open("G:\\user.csv", "a") as f:
        f.write(x)
    print(u"生成第[%d]个账号"%(i))

(2)运行后的结果如下

生成csv文件

以上就是利用Python代码读取和写入txt,csv文件操作,小伙伴们学会了吗?

分类:

技术点:

相关文章: