打開文件:
open()函數:
open(文件名,訪問模式)?????? f = open('文件名','訪問模式')
說明:
關閉文件:
close()函數:
close('文件名')???????? f.close():
路徑:
路徑中的/解決法:
文件讀寫:
寫數據:
write:??????? 示例:f.write('你好,python')
讀數據:
read(長度):?? 示例:content = f.read()
注意:如果文件被讀取過,那么下次讀取是從上次讀取結束的位置上開始讀取
readlines:按照行的讀取方式進行一次性讀取,并且返回的是個列表
示例:
f = open('test.txt','r')
content = f.readlines()
print(content)
讀數據:readline
備份:
示例
oldname = input('請輸入你要備份的文件:')
oldfile=open(oldname,'rb')
content=oldfile.read()
newname=oldname[:oldname.rfind('.')]+'-備份'+oldname[oldname.rfind('.'):]
newfile=open(newname,'wb')
newfile.write(content)
文件的隨機讀寫:
獲取當前讀寫的位置:tell()????? 從0開始,到文件內字符的個數
示例:
#打開一個已經存在的文件
f = open("test.txt","r")
str = f.read(3)
print("讀取的數據是: ", str)
#查找當前位置
position = f.tell()
定位到某個位置:
seek()
seek(offset, from)有2個參數
1.offset:偏移量(跳過字符,從那個地方開始讀取)
2.from:方向,從哪個位置開始,用0
0:表示文件開頭(python3)
文件重命名:rename(‘需要修改的名稱’,‘修改之后的新名稱’)
importos
os.rename("畢業論文.txt","畢業論文-最終版.txt")
刪除文件:remove(要刪除的文件名)
importos
os.remove("畢業論文.txt")
??