涉及文本操作就會涉及到編碼解碼問題,編碼方式的歷史大致為ASCII ->gb2312->unicode->utf-8,期間具體詳細(xì)信息可以百度
來個編碼解碼的小例子先:
bytes = '張三'.encode('GBK')
print(bytes)
print(type(bytes))
byte_utf8 = "張三".encode('utf-8')
print(byte_utf8)
string = bytes.decode('GBK')
print(string)
string = byte_utf8.decode("GBK")
print(string)
b'\xd5\xc5\xc8\xfd'
<class 'bytes'>
b'\xe5\xbc\xa0\xe4\xb8\x89'
張三
寮犱笁
可以發(fā)現(xiàn),編碼解碼格式不一致可能會出現(xiàn)亂碼,encode表示編碼
- 文件操作流程
1.打開文件,得到文件句柄并賦值給一個變量
2.通過句柄對文件進(jìn)行操作
3.關(guān)閉文件
簡單格式如下:
f=open('test.txt',encoding='utf-8') #打開文件
data=f.read() #文件操作
print(data)
f.close() #關(guān)閉文件
- open()函數(shù)的具體用法:
open函數(shù)最常用的使用方法如下:文件句柄 = open('文件路徑', '模式',編碼方式)。
- 文件路徑
文件路徑:主要有兩種,一種是使用相對路徑,想上面的例子就是使用相對路徑。另外一種就是絕對路徑,像' C:/Users/shu/Desktop/python/test.txt' - 打開模式

關(guān)閉文件
不要小看這一步,因?yàn)槲覀冏x取文件是把文科讀取到內(nèi)存中的,如果我們沒關(guān)閉它,它就會一直占用系統(tǒng)資源,而且還可能導(dǎo)致其他不安全隱患。還有一種方法可以讓我們不用去特意關(guān)注關(guān)閉文件。那就是 with open()-
打開文件的類型介紹
可以打開文本文件和二進(jìn)制文件,文本文件本質(zhì)上存儲時(shí),也是二進(jìn)制文件。但可以用文本編輯器查看。二進(jìn)制文件,無法通過文本編輯器查看
讀文件三種方法
- read()
特點(diǎn)是:讀取整個文件,將文件內(nèi)容放到一個字符串變量中。
劣勢是:如果文件非常大,尤其是大于內(nèi)存時(shí),無法使用read()方法。
實(shí)例如下:
file = open('兼職模特聯(lián)系方式.txt', 'r') # 創(chuàng)建的這個文件,也是一個可迭代對象
try:
text = file.read() # 結(jié)果為str類型
print(type(text))
print(text)
finally:
file.close()
"""
<class 'str'>
吳迪 177 70 13888888
王思 170 50 13988888
白雪 167 48 13324434
黃蓉 166 46 13828382
"""
>>> file = open('兼職模特聯(lián)系方式.txt', 'r')
>>> a = file.read()
>>> a
'吳迪 177 70 13888888\n王思 170 50 13988888\n白雪 167 48 13324434\n黃蓉 166 46 13828382'
read()直接讀取字節(jié)到字符串中,包括后面的換行符
- readline()方法
特點(diǎn):readline()方法每次讀取一行;返回的是一個字符串對象,保持當(dāng)前行的內(nèi)存
缺點(diǎn):比readlines慢得多
file = open('兼職模特聯(lián)系方式.txt', 'r')
try:
while True:
text_line = file.readline()
if text_line:
print(type(text_line), text_line)
else:
break
finally:
file.close()
"""
<class 'str'> 吳迪 177 70 13888888
<class 'str'> 王思 170 50 13988888
<class 'str'> 白雪 167 48 13324434
<class 'str'> 黃蓉 166 46 13828382
"""
>>> file = open('兼職模特聯(lián)系方式.txt', 'r')
>>> a = file.readline()
>>> a
'吳迪 177 70 13888888\n'
readline() 讀取整行,包括行結(jié)束符,并作為字符串返回
- readlines()方法
特點(diǎn):一次性讀取整個文件;自動將文件內(nèi)容分析成一個行的列表。
缺點(diǎn):若一個文件特別大,name一次性將文件都讀入內(nèi)存,容易奔潰
file = open('兼職模特聯(lián)系方式.txt', 'r')
try:
text_lines = file.readlines()
print(type(text_lines), text_lines)
for line in text_lines:
print(type(line), line)
finally:
file.close()
"""
<class 'list'> ['吳迪 177 70 13888888\n', '王思 170 50 13988888\n', '白雪 167 48 13324434\n', '黃蓉 166 46 13828382']
<class 'str'> 吳迪 177 70 13888888
<class 'str'> 王思 170 50 13988888
<class 'str'> 白雪 167 48 13324434
<class 'str'> 黃蓉 166 46 13828382
"""
>>> file = open('兼職模特聯(lián)系方式.txt', 'r')
>>> a = file.readlines()
>>> a
['吳迪 177 70 13888888\n', '王思 170 50 13988888\n', '白雪 167 48 13324434\n', '黃蓉 166 46 13828382']
以上部分內(nèi)容摘自博客:https://www.cnblogs.com/xiugeng/p/8635862.html
- 文件寫方法:write、writelines
write和writelines的區(qū)別
1 write()需要傳入一個字符串做為參數(shù),否則會報(bào)錯
2 writelines()既可以傳入字符串又可以傳入一個字符序列,并將該字符序列寫入文件
注意 :writelines必須傳入的是字符序列,不能是數(shù)字序列
如:list_1023 = [1,2,3,4,5]
報(bào)錯:TypeError: write() argument must be str, not list
其余用法很多類似于讀操作
附上文件操作的作業(yè):
# 作業(yè)1:創(chuàng)建文件:data.txt,一共10000行,每行存放一個1-100間的整數(shù)。
# 作業(yè)2:找出文件中數(shù)字出現(xiàn)最多的十個數(shù)字。
# 寫入到文件mostNum.txt中。可用collections.counter
from random import randint
from collections import Counter
count_list = Counter(['b', 'a', 'a', 'b', 'a', 'c', 'b', 'b'])
print(count_list)
count_tuple = Counter((1,4,3,4,1,3,2,2,1))
print(count_tuple)
with open('data.txt', 'w') as f:
for i in range(10000):
f.write(str(randint(1,101)) + '\n')
with open('data.txt', 'r') as f:
content = []
line = f.readline()
while line:
content.append(line[:-1])
line = f.readline()
count_list = Counter(content)
most_count_list = count_list.most_common(10)
print(most_count_list)
for i in range(10):
print(most_count_list[i][0])
Counter({'b': 4, 'a': 3, 'c': 1})
Counter({1: 3, 4: 2, 3: 2, 2: 2})
[('86', 124), ('48', 122), ('72', 121), ('98', 121), ('5', 115), ('24', 115), ('68', 114), ('13', 114), ('93', 114), ('27', 112)]
86
48
72
98
5
24
68
13
93
27
