一、文件的基本操作
文件內容:
Somehow, it seems the love I knew was always the most destructive kind
不知為何,我經歷的愛情總是最具毀滅性的的那種
Yesterday when I was young
昨日當我年少輕狂
?1、read()
當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
注:只有當文件有讀權限時,才可以操作這個函數
2、tell()
獲取文件句柄所在的指針的位置
f = open("yesterday2",'r',encoding="utf-8")
print(f.read(10))
#獲取指針位置
print(f.tell())
f.close()
#輸出
Somehow, i #讀取的內容
10 #指針位置
?3、seek()
設置文件句柄所在的指針位置
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 #設置之后的指針位置
?4、encoding
打印文件的編碼
f = open("yesterday2",'r',encoding="utf-8")
print(f.encoding)
f.close()
#輸出
utf-8
?5、fileno()
返回文件句柄在內存中的編號
f = open("yesterday2",'r',encoding="utf-8")
print(f.fileno())
f.close()
#輸出
3
?6、name
返回文件名
f = open("yesterday2",'r',encoding="utf-8")
print(f.name)
f.close()
#輸出
yesterday2
?7、isatty()
判斷是否是一個終端設備(比如:打印機之類的)
f = open("yesterday2",'r',encoding="utf-8")
print(f.isatty())
f.close()
#輸出
False #表示不是一個終端設備
?8、seekable()
?不是所有的文件都可以移動光標,比如tty文件,可以移動的,返回True
f = open("yesterday2",'r',encoding="utf-8")
print(f.seekable())
f.close()
#輸出
True
?9、readable()
文件是否可讀
f = open("yesterday2",'r',encoding="utf-8")
print(f.readable())
f.close()
#輸出
True
?10、writeable()
文件是否可寫
f = open("yesterday2",'r',encoding="utf-8")
print(f.writable())
f.close()
#輸出
False #文件不可寫
?11、flush()
寫數據時,寫的數據不想存內存中緩存中,而是直接存到磁盤上,需要強制刷新
>>> f = open("yesterday2","w",encoding="utf-8")
#這時'hello word'在緩存中
>>> f.write("hello word")
10
#強刷到磁盤上
>>> f.flush()
?這個怎么實驗呢?在cmd命令行中,cd到你文件所在的路徑下,然后輸入python,在Python命令行中輸入上面代碼
①cd d:\PycharmProjects\pyhomework\day3下(因為我的被測文件在這個文件夾下)
②在這個目錄下輸入Python命令行,然后進行測試
③強制刷新之前
?④執行強刷命令之后
?
⑤強刷后文件中的內容變化
?
注:以寫的模式打開文件,寫完一行,默認它是寫到硬盤上去的,但是其實它不一定寫到硬盤上去了。當你剛寫完一行,如果此時斷電,有可能,你這行就沒有寫進去,因為這一樣還在內存的緩存中(內存中的緩存機制),所以你有不想存緩存,所以就要強制刷新。那一般在什么情況下用吶?比如:存錢
12、closed
判斷文件是否關閉
f = open("yesterday2","r",encoding="utf-8")
f.read()
print(f.closed)
#輸出
False
?13、truncate(截取字符的數)
截取文件中的字符串,打開文件模式一定是追加模式(a),不能是寫(w)和讀(r)模式
#沒有指針
f = open("yesterday2","a",encoding="utf-8")
f.truncate(10)
f.close()
#截取結果
Somehow, i#有指針
f = open("yesterday2","a",encoding="utf-8")
f.seek(5)
f.truncate(10)
f.close()
#截取結果
Somehow, i
?說明truncate截取文件中的字段,并不受指針(seek)所在位置影響。
14、write()
寫入文件內容
f = open("yesterday2","w",encoding="utf-8")
f.write("Somehow, it seems the love I knew was always the most destructive kind")
f.close()
?注:寫功能只有當打開文件模式是寫(w)或者追加(a)才可操作。
?