Python read和write方法


Python read和write方法:

read():

從文件中讀取字符串

注:Python 字符串可以是二進制數據,而不僅僅是文字。

語法:

文件對象.read([count])

count:打開文件需要讀取的字符數

注:read 函數不使用 count 會盡可能多地讀取更多的內容,通常一直讀取到文件末尾。

程序:

# 打開創建好的 test.txt 文件 f = open("test.txt",'r') # 輸出文件所有的內容 print(f.read()) # 關閉文件 f.close() # hello,world. # hello,world2. # hello,world3. # hello,world4. # hello,world5. # hello,world6. # hello,world7. # hello,world8. # hello,world9. # 使用 count # 打開創建好的 test.txt 文件 f = open("test.txt",'r') # 輸出文件的前 11 個字符 print(f.read(11)) # ['hello,world.\n'] # 關閉文件 f.close() # hello,world

文件位置:

tell():

返回文件內當前指向的位置

# 使用 count # 打開創建好的 test.txt 文件 f = open("test.txt",'r') # 輸出文件的前 11 個字符 print(f.read(11)) # 返回文件內當前指向的位置 print(f.tell()) # 11 # 關閉文件 f.close() # hello,world

seek(offset [,from]):

改變當前文件的位置

  offset:表示要移動的字節數

  from :指定開始移動字節的參考位置。

    0:文件開頭

    1:當前位置

    2:文件末尾

程序:

# 打開創建好的 test.txt 文件 f = open("test.txt",'r') # 輸出文件的前 11 個字符 print(f.read(11)) # hello,world # 返回文件內當前指向的位置 print(f.tell()) # 11 print(f.seek(0,0)) # 0 print(f.tell()) # 0 print(f.read(11)) # hello,world # 關閉文件 f.close()

write( ):

將任意字符串寫入一個文件中

注:Python字符串可以是二進制數據 和 文字,換行符('\n') 需要自己添加

語法:

文件對象.write(字符串)

程序:

# write 方法 # 打開創建好的 test.txt 文件  f = open("test.txt",'w') # 在開頭,添加文件內容 f.write('hey boy') # 關閉文件 f.close()

 


2020-02-14


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM