Python读取和写入txt,csv文件数据
前言
小伙伴們在使用python做接口自動化測試的時候,需要創(chuàng)建數(shù)據(jù)文件進行參數(shù)化,那么Python如何讀取和寫入txt,csv的文件數(shù)據(jù)呢?今天我們一起來學(xué)習(xí)一下吧!
一:讀取txt文件數(shù)據(jù)
(1)創(chuàng)建txt數(shù)據(jù)文件,創(chuàng)建好文件記得要關(guān)閉文件,不然讀取不了文件內(nèi)容
(2)打開PyCharm,,創(chuàng)建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)運行后的結(jié)果如下
二:讀取csv文件數(shù)據(jù)
(1)創(chuàng)建txt數(shù)據(jù)文件,創(chuàng)建好文件要關(guān)閉該文件,不然讀取不文件內(nèi)容
注:先創(chuàng)建txt的文件,然后另存為csv后綴文件
(2)打開PyCharm,,創(chuàng)建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]) #數(shù)組下標是以0開始的
(3)運行后的結(jié)果如下
三:寫入數(shù)據(jù)到txt文件
(1)打開PyCharm,,創(chuàng)建python file ,寫入以下代碼
import random
import string#--------寫入txt文件
#生成小寫字母和數(shù)字的混合字符串
# 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']
#生成大小字母和數(shù)字一起的大字符串
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) + '
'
with open("G:\user.txt", "a") as f:
f.write(x)
print(u"生成第[%d]個賬號"%(i))
(2)運行后的結(jié)果如下
生成txt文件
三:寫入數(shù)據(jù)到csv文件
(1)打開PyCharm,,創(chuàng)建python file ,寫入以下代碼
import random
import string
import csv#--------寫入csv文件
#生成小寫字母和數(shù)字的混合字符串
# 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']
#生成大小字母和數(shù)字一起的大字符串
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) + '
'
with open("G:\user.csv", "a") as f:
f.write(x)
print(u"生成第[%d]個賬號"%(i))
(2)運行后的結(jié)果如下
生成csv文件
以上就是利用Python代碼讀取和寫入txt,csv文件操作,小伙伴們學(xué)會了嗎?
總結(jié)
以上是生活随笔為你收集整理的Python读取和写入txt,csv文件数据的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 安装 Windows 10 系统时分区选
- 下一篇: 优盘中毒后文件不见了,如何恢复