python基礎之文件操作(基礎六)


第八章python基礎之文件操作(基礎六)

python的文件的讀寫通過python的open()函數來打開一個文件。

打開方式: r, w, a, r+, w+, a+, rb, wb, ab, r+b, w+b, a+b 默認使⽤用的是r(只讀)模式

8.1 文件初識

f = open("文件路徑",mode="模式",encoding="編碼")

open()	打開文件
open("文件的路徑")
open(mode= "對文件的操作方式")
open(encoding="utf-8")
編碼:win==>gbk,Linux==>utf-8,mac==>utf-8
f = pen()文件的句柄

open() # 調用操作系統打開文件
mode # 對文件的操作方式
encoding # 文件的編碼集 -- 存儲編碼要統一,根據⽂文件的實際保存編碼進⾏行行獲取數據

8.1文件的讀操作

文件全部讀取完成以后,在次讀取就沒有內容

只讀 r 模式:

f = open("a",mode="r",encoding="gbk")
content = f.read()    # 全部讀取
print(content)
c1 = f.read(3)        # 字符讀取
print(f.readline(3))  # 讀取一行內容中多個字符
print(f.readlines())  # 一行一行讀取,存儲到列表中   \n是換行
print(f.read())

文件的路徑與查找:

F:\a\111.txt  		絕對路徑 從磁盤的根處查找
相對路徑      		相對於當前文件進行查找的

import os
print(os.getcwd())  # 查看當前工作路徑

print(repr("F:\a\文件初識.txt"))
print("F:\a\文件初識.txt")

文件的迭代讀取

for i in f:  # 迭代讀取
    print(i)

8.2 文件的寫操作

文件寫 w 模式:w清空寫入,a 追加寫在文本末尾添加

沒有文件創建文件內容,有文件內容清空內容在寫入

f = open("day8",mode="w",encoding="utf-8")  #打開文件
f.write("123")							 #操作文件
f.close()  								 # 關閉文件
f = open("a",mode="r",encoding="gbk")
print(f.read())
f.close()  # 關閉文件后就不能繼續讀取了

寫入文件內容:f.write("寫入的內容")

f = open("a",mode="a",encoding="gbk")
f.write("啊啊啊,好困啊")						#文件末尾添加

8.3文件的非文本讀寫操作

rb,wb,ab 不能指定編碼

f = open("1.jpg",mode="rb")		#打開圖片格式文件
rb ,wb,ab 不能指定編碼
print(f.read())  # read()  全部讀取
print(f.read(3)) # 字節

通過requests模塊爬取圖片文件

import requests
ret = requests.get("http://www.521609.com/uploads/allimg/151124/1-1511241G251317.png")
f = open("2.jpg",mode="wb")
f.write(ret.content)
f.close()

8.4文件的r+,w+,a+模式操作

r 讀 r+ 讀寫
w 寫 w+ 寫讀
a 寫 a+ 寫讀

錯誤示范
f = open("day8",mode="r+",encoding="utf-8")
f.write("你好啊")
print(f.read())

正確示范   -- 后期開發中使用頻率比較低
f = open("day8",mode="r+",encoding="utf-8")
print(f.read())
f.write("腦瓜疼啊腦瓜疼")

w+ 寫讀

f = open("day8",mode="w+",encoding="utf-8")
f.write("你您你你")
print(f.read())

a+ 追加

f = open("a",mode="a+",encoding="gbk")
print(f.tell())  # 查看的是字節
f.seek(0)
print(f.read(1)) # 字符

其他操作

查看光標: tell() 返回值 返回的就是當前光標的位置

移動光標::

  seek(0,0) 文件開始位置
  seek(0,1) 光標的當前位置
  seek(0,2) 文件末尾位置
  seek(3)   按照字節調節  使用utf-8是3 gbk是2

8.5文件的修改

with open("day8",mode="r+",encoding="utf-8")as f:
    content = f.read()
    content = content.replace("您","你")
    f.seek(0,0)
    f.write(content)

文件的修改:

with open("day8",mode="r",encoding="utf-8")as f,\
open("new_day8",mode="a",encoding="utf-8")as f1:
    for i in f:
        content = i.replace("你","我")
        f1.write(content)

import os
os.remove("day8")  # 原數據可以使用rename來做備份
os.rename("new_day8","day8")

有問題用for循環批量修改文件需要修改的內容:

with open("day8",mode="r+",encoding="utf-8")as f:
    for i in f:
        content = i.replace("您","你")
        f.seek((0,0))
        f1.write(content)



免責聲明!

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



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