python文件操作

涉及文本操作就會涉及到編碼解碼問題,編碼方式的歷史大致為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('文件路徑', '模式',編碼方式)。
  1. 文件路徑
    文件路徑:主要有兩種,一種是使用相對路徑,想上面的例子就是使用相對路徑。另外一種就是絕對路徑,像' C:/Users/shu/Desktop/python/test.txt'
  2. 打開模式
  • 關(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)制文件,無法通過文本編輯器查看


  • 讀文件三種方法

  1. 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é)到字符串中,包括后面的換行符

  1. 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é)束符,并作為字符串返回

  1. 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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Python文件操作 準(zhǔn)備工作: 1) 使用python來讀取文件是非常簡單的操作,我們使用open()函數(shù)來打開...
    小學(xué)弟_閱讀 578評論 0 0
  • 目標(biāo) 文件的概念 文件的基本操作 文件/文件夾的常用操作 文本文件的編碼方式 01. 文件的概念 1.1 文件的概...
    __元昊__閱讀 237評論 0 1
  • 目標(biāo) 文件的概念 文件的基本操作 文件/文件夾的常用操作 文本文件的編碼方式 01. 文件的概念 1.1 文件的概...
    極課編程閱讀 473評論 0 5
  • 一.文件IO常用操作 二.open open(file, mode='r', buffering=-1, enco...
    秋幻旎蘇閱讀 344評論 0 0
  • 楊貴云焦點(diǎn)43期堅(jiān)持原創(chuàng)分享第72天平頂山 今天是周四公益課,由呂素英老師主講。聚焦現(xiàn)在和未來---做最好的自己。...
    舒靜心閱讀 480評論 0 0

友情鏈接更多精彩內(nèi)容