2018-10-25
閱讀量:
1277
Python文件類型
1、常用的文件編碼類型

2、Python讀取文件
Python讀取文件包括兩步:文件打開+文件讀取
文件打開代碼示例:infile = open(“numbers.dat”,”r”)
文件打開模式如下:

文件讀取代碼示例:data = infile.read()
文件讀取方法如下:

Python讀取文件示例
# test01.txt 文件內(nèi)容如下
1 2 3
4 5 6
7 8 9
# 讀取文件全部內(nèi)容
fname = "D:\\test01.txt" #確保D盤下有test.txt文件
infile = open(fname,"r")
data = infile.read()
# 上述兩條代碼也可合并成:data = open(fname,"r").read() #建議分開寫
print(data)
# 輸出結(jié)果
1 2 3
4 5 6
7 8 9
# 遍歷讀取文件全部內(nèi)容
infile = open(fname,"r")
for line in infile:
print(line)
# 輸出結(jié)果
1 2 3
4 5 6
7 8 9
# 讀取文件前n行內(nèi)容
fname = "D:\\test01.txt"
infile = open(fname,"r")
for i in range(2): #讀取文件前幾行
data = infile.readline()
print(data)
# 輸出結(jié)果
1 2 3
4 5 6
# 從第2行開始讀取文件內(nèi)容(多用于去除表頭)
fname = "D:\\tes01.txt"
infile = open(fname,"r")
infile.readline() #去除表頭
data = infile.readlines() #以列表方式讀取
print(data)
# 輸出結(jié)果
4 5 6
7 8 9
3、
Python寫入文件
outfile = open("D:\\test02.txt","w") #在D盤建一個(gè)名為test02的文件,若存在則不會(huì)創(chuàng)建
outfile.writelines(["Hello"," ","World"]) #寫入數(shù)據(jù)
outfile.close()
infile = open("D:\\test02.txt","r").read() #讀取數(shù)據(jù)
print(infile)
# 輸出結(jié)果
Hello World
Python文件寫入方法如下:

4、Python多個(gè)文件合并
# ==== 原始文件 ====
a1.txt
姓名 電話
王五 123456
張三 456789
李四 789456
熊七 456123
a2.txt
姓名 郵箱
王五 feifei1@qq.com
勝八 feifei2@qq.com
張三 feifei3@qq.com
章九 feifei4@qq.com
# ==== Python代碼 ====
# 原始數(shù)據(jù)讀入
ftele1=open('d:\\a1.txt','rb') #采用二進(jìn)制方式讀取,避免中文亂碼
ftele2=open('d:\\a2.txt','rb')
ftele1.readline() #去除表頭變量名
ftele2.readline()
lines1 = ftele1.readlines()
lines2 = ftele2.readlines()
list1_name = []
list1_tele = []
list2_name = []
list2_email = []
for line in lines1: #獲取a1文件中的姓名和電話信息
elements = line.split()
list1_name.append(str(elements[0].decode('gbk'))) #采用gbk中文編碼讀入
list1_tele.append(str(elements[1].decode('gbk'))) #str()將文本讀出來的bytes轉(zhuǎn)換為字符類型
for line in lines2: #獲取a2文件中的姓名和郵件信息
elements = line.split()
list2_name.append(str(elements[0].decode('gbk')))
list2_email.append(str(elements[1].decode('gbk')))
# 創(chuàng)建空白文件
lines = []
lines.append('姓名\t 電話 \t 郵箱\n')
#按索引方式遍歷姓名列表1
for i in range(len(list1_name)):
s= ''
if list1_name[i] in list2_name:
j = list2_name.index(list1_name[i]) #找到姓名列表1對應(yīng)列表2中的姓名索引位置
s = '\t'.join([list1_name[i], list1_tele[i], list2_email[j]])
s += '\n'
else:
s = '\t'.join([list1_name[i], list1_tele[i], str(' ----- ')])
s += '\n'
lines.append(s)
#處理姓名列表2中剩余的姓名
for i in range(len(list2_name)):
s= ''
if list2_name[i] not in list1_name:
s = '\t'.join([list2_name[i], str(' ----- '), list2_email[i]])
s += '\n'
lines.append(s)
ftele3 = open('d:\\a3.txt', 'w') #將數(shù)據(jù)寫入文件
ftele3.writelines(lines)
ftele3.close()
ftele1.close()
ftele2.close()
# ==== 輸出結(jié)果 ====
姓名 電話 郵箱
王五 123456 feifei1@qq.com
張三 456789 feifei3@qq.com
李四 789456 -----
熊七 456123 -----
勝八 ----- feifei2@qq.com
章九 ----- feifei4@qq.com






評論(0)


暫無數(shù)據(jù)
CDA考試動(dòng)態(tài)
CDA報(bào)考指南
推薦帖子
0條評論
0條評論
0條評論