[Python Study Notes]文件操作
阿新 • • 發佈:2018-01-09
content span 文件 鏡像文件 學習 chapter line ont con
文件操作
對文件操作流程
- 打開文件,可添加filepath打開某絕對路徑下的文件,得到文件句柄並賦值給一個變量
- 通過句柄對文件進行操作
- 關閉文件
1 # The_author = ‘liu66‘ 2 # -*- coding = utf-8 -*- 3 4 filepath=‘D:\學習資料\ehmatthes-pcc-6bfeca0\chapter_10\pi_digits.txt‘ 56 read_sting = ‘‘ 7 8 with open(filepath) as file_object: 9 #contents=file_object.read() 10 # print(contents) 11 # ‘‘‘刪除末尾空行‘‘‘ 12 # print(contents.rstrip()) 13 14 ‘‘‘逐行打印‘‘‘ 15 for line in file_object: 16 # ‘‘‘兩行空白,一行來自文件,一行來自print‘‘‘ 17 # print(line) 18# ‘‘‘去掉文件換行‘‘‘ 19 # print(line.rstrip()) 20 21 ‘‘‘刪除所有空格‘‘‘ 22 read_sting+=line.strip() 23 file_object.close() 24 print(read_sting) 25 print(len(read_sting))
打開文件的模式有:
- r,只讀模式(默認)。
- w,只寫模式。【不可讀;不存在則創建;存在則刪除內容;】
- a,追加模式。【可讀; 不存在則創建;存在則只追加內容;】
"+" 表示可以同時讀寫某個文件
- r+,可讀寫文件。【可讀;可寫;可追加】
- w+,寫讀
- a+,同a
"U"表示在讀取時,可以將 \r \n \r\n自動轉換成 \n (與 r 或 r+ 模式同使用)
- rU
- r+U
"b"表示處理二進制文件(如:FTP發送上傳ISO鏡像文件,linux可忽略,windows處理二進制文件時需標註)
- rb
- wb
- ab
[Python Study Notes]文件操作