1、文件常用操作匯總
2、打開文件
3、操作文件
4、關閉文件
文件內容:
Somehow, it seems the love I knew was always the most destructive kind不知為何,我經歷的愛情總是最具毀滅性的的那種Yesterday when I was young昨日當我年少輕狂
當read()函數中傳入整數(int)參數,則讀取相應的字符數,如果不填寫,則默認讀取所有字符
f = open("yesterday2",'r',encoding="utf-8")#默認讀取全部字符print(f.read())f.close()#輸出Somehow, it seems the love I knew was always the most destructive kind不知為何,我經歷的愛情總是最具毀滅性的的那種Yesterday when I was young昨日當我年少輕狂 f = open("yesterday2",'r',encoding="utf-8")#只讀取10個字符print(f.read(10))f.close()#輸出Somehow, i
注:只有當文件有讀權限時,才可以操作這個函數
獲取文件句柄所在的指針的位置
f = open("yesterday2",'r',encoding="utf-8")print(f.read(10))#獲取指針位置print(f.tell())f.close()#輸出Somehow, i #讀取的內容10 #指針位置
f = open("yesterday2",'r',encoding="utf-8")print(f.read(10))#設置之前的指針位置print(f.tell())f.seek(0)#設置之后的指針位置print(f.tell())f.close()#輸出Somehow, i #讀取文件的內容10 #設置之前的指針位置0 #設置之后的指針位置
f = open("yesterday2",'r',encoding="utf-8")print(f.encoding)f.close()#輸出utf-8
返回文件句柄在內存中的編號
f = open("yesterday2",'r',encoding="utf-8")print(f.fileno())f.close()#輸出3
返回文件名
f = open("yesterday2",'r',encoding="utf-8")print(f.name)f.close()#輸出yesterday2
判斷是否是一個終端設備(比如:打印機之類的)
新聞熱點
疑難解答