Python學習筆記——讀寫相關的os、pickle、StringIO、BytesIO模塊

內容整理自廖雪峯官網和學習視頻

os

import os #系統模塊-常用命令

print(os.name)#輸出正在使用的平臺 windows-nt

print(os.getcwd())#當前目錄名

print(os.listdir())#返回指定目錄的文件夾中所有文件

os.chdir(‘C:\Users\Violette\Desktop\’)#更改當前所在目錄

os.remove(‘test.txt’)#刪除當前目錄下的文件

os.path.splitext()#將文件名和擴展名分開

os.path.split()#將文件路徑和文件名分開

os.path.exists(‘C:/Users/Violette/Desktop/test.txt’)#判斷文件或路徑是否存在,存在傳回

pickle

pickle模塊
數據序列化,將程序中運行的對象信息以pkl格式儲存在磁盤上
反序列化,從文件中創建上一次程序保存的對象
pickle.dump()、pickle.load()

import pickle

l={'AAA':111,'BBB':222,'CCC':333}
print(l)
#存儲 'wb' 'pickle.dump()'
pic=open('data.pkl','wb')#生成的pkl文件可能是亂碼,但是可以被讀取爲字典
pickle.dump(l,pic)#寫入內容和寫入的文件
pic.close()
#讀取 'rb' 'pickle.load()'
pic=open('data.pkl','rb')
d=pickle.load(pic)
print(d)
內存讀寫

內存中讀寫str或bytes

StringIO

注意str.strip在讀寫中這個用法

from io import StringIO
#寫入
f1 = StringIO()#先創建
f1.write('Love')#write寫入str
f1.write(' Python')
print(f1.getvalue())#getvalue()獲取寫入後str
#Love Python
f1.close()

#讀取
f = StringIO('Still\n Moving\nUnder\nGunfire')
while True:
    s = f.readline()#按行讀取
    if s == '':
        break
    print(s.strip())
    #strip移除字符串頭尾指定的字符(默認爲空格或換行符)或字符序列
    #只能刪除開頭或結尾的字符
'''
Love Python
Still
Moving
Under
Gunfire
'''
BytesIO

操作二進制數據,讀寫bytes
這部分沒有實操 就直接複製了廖雪峯

#寫
>>> from io import BytesIO
>>> f = BytesIO()
>>> f.write('中文'.encode('utf-8'))
6>>> print(f.getvalue())
b'\xe4\xb8\xad\xe6\x96\x87'
#讀
>>> from io import BytesIO
>>> f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
>>> f.read()
b'\xe4\xb8\xad\xe6\x96\x87'
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章