# 文件操作
#打開颠毙,關(guān)閉文件(open,close)
#分路徑民傻,相對路徑想幻,絕對路徑
#相對路徑 9.文件操作.txt? 在當(dāng)前使用的路徑下尋找改文件
#絕對路徑 C:\Users\ASUS\Desktop\py筆記\9.文件操作.txt
#r 以只讀方式打開,文件指針默認(rèn)放在文件開頭
#r+ 打開一個文件用于讀寫弥虐,指針放于開頭
#w 以只寫形式打開扩灯,文件存在則覆蓋,不存在則創(chuàng)建
#w+ 打開一個文件用于讀寫霜瘪,文件存在則覆蓋珠插,不存在則創(chuàng)建
#a? 以追加形式打開文件,指針在文件結(jié)尾颖对,不存在則創(chuàng)建新文件
#a+ 打開一個文件用于讀寫捻撑,指針在文件結(jié)尾,不存在則創(chuàng)建新文件
#后加b代表以二進(jìn)制格式打開文件-》音頻缤底,圖片顾患,視頻是以二進(jìn)制方式打開的
#文本模式,是以str進(jìn)行
## 方法
f.read() 讀取指定大小的內(nèi)容
f.readline() 讀取一行內(nèi)容
f.readlines() 讀取多行內(nèi)容
f.write(data) 寫入內(nèi)容
f.writelines(lines) 寫入多行內(nèi)容个唧,需要自己加換行符
f.flush() 立即刷新緩沖
f.tell() 獲得指針位置
f.seek(positon) 調(diào)整指針位置 0為初始位
a=r'C:\Users\ASUS\Desktop\py'
b=r'\9.文件操作.txt'
fp=open(a+b,'r')
print(fp.read())
fp.seek(1)#->調(diào)整指針位置
print(fp.readline())
print(fp.readlines())
fp.close()
fp=open(a+b,'w+')
fp.write('hello\nop')
## 文件存到內(nèi)存當(dāng)中 臨時存放東西的 重啟后內(nèi)存中的數(shù)據(jù)消失不見
import? io
myio=io.StringIO()
myio.write('hello')
print(myio.getvalue())
print(myio.getvalue())#可重復(fù)讀取數(shù)據(jù)
myio.close()#關(guān)閉描验,清除數(shù)據(jù)
# print(myio.getvalue())#關(guān)閉后無法讀取
#二進(jìn)制數(shù)據(jù)
myio=io.BytesIO()
myio.write('hello'.encode())
print(myio.getvalue())
## 上下文管理
with open(a+b,'r+') as f:#自動關(guān)閉文件
? ? # f.write('hello nihao')
? ? f.seek(0)
? ? print(f.read())
with open(a+b,'r+') as fp,\
? ? open(a+r'\o.txt','w+',encoding='utf-8') as? fp1:
? ? ? ? ? fp.write('nihao')
? ? ? ? ? fp1.write('hello')
? ? ? ? ? # fp.flush()
? ? ? ? ? fp.seek(0)
? ? ? ? ? print(fp.read())
? ? ? ? ? print(fp1.read())
__enter__和 __exit__
__enter__ 進(jìn)入的時候自動調(diào)用 在使用with as內(nèi)代碼前調(diào)用
__exit__? 退出的時候自動調(diào)用 with as里面的代碼執(zhí)行完后調(diào)用
class A:
? ? def __enter__(self):
? ? ? ? print("進(jìn)入的時候自動調(diào)用 使用with as內(nèi)代碼")
? ? ? ? fp=open(a+r'\9.文件操作.txt','r')
? ? ? ? print(fp.read())
? ? ? ? return fp#with as 設(shè)定的指針
? ? def __exit__(self, exc_type, exc_val, exc_tb):
? ? ? ? print('退出的時候自動調(diào)用 with as 里面的代碼執(zhí)行完')
? ? ? ? fp.close()#這里的指針名對應(yīng)with as的指針
# H=A()
with A() as fp:
? ? print(1111)
## 兩個常用參數(shù)
#errors=ignore->忽略錯誤輸出,出錯忽略
#encoding=什么編碼格式
# with open(a+r'\9.文件操作.txt','r',encoding='ASCII',errors='ignore') as f:
#? ? print(f.read())
## os 文件和目錄(文件夾)
#import os
#print(os.getcwd())#顯示當(dāng)前路徑
#print(os.listdir(r'C:\Users\ASUS\PycharmProjects\untitled2\venv'))#顯示當(dāng)前路徑下的所有文件
#os.chdir()#改變當(dāng)前路徑
#os.mdikr(r'D:\aaa')#創(chuàng)建一個新文件夾aaa
#os.rmdir(r'D:\aaa')#刪除該文件
#os.remove(r'文件地址')#刪除指定路徑下的文件
#os.rename('a.txt','aa.txt')#文件名替換
#解釋器在Windows上面可以使用Windows命令坑鱼,如果在linux上面就可以使用linux命令
#當(dāng)我嗎用open w的方式創(chuàng)建文件時,如果解釋器在linux上 文件就在Linux上絮缅,本地不會有
#os.system()
### os.path模塊
#os.path.join(r'C:\','wer\ty\op.txt')#路徑拼接
#os.path.relpath(r'a.txt')#查相對路徑
#os.path.abspath(r'a.txt')#查絕對路徑
#os.path.isabs()#是否為絕對路徑