前言
小伙伴們在使用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文件操作,小伙伴們學會了嗎?