【python----文件的打開】 -- open 操作


# open 參數介紹 # file :用來指定打開的文件(不是文件的名字,而是文件的路徑) # mode :打開文件時的模式,默認是r表示 只讀 # encoding:打開文件時的編碼方式 # file.read() 讀取文件 # file.close() c操作完成文件后,關閉文件 # tell 告訴 seek 查找 write 寫 flush 沖刷 刷新 buffering 刷新 #  # r' open for reading (default) # 'w' open for writing, truncating the file first # 'x' create a new file and open it for writing # 創建一個新文件 並 寫 # 'a' open for writing, appending to the end of the file if it exists # # 'b' binary mode # 二進制 # 't' text mode (default) # 以文本操作 # '+' open a disk file for updating (reading and writing) # 讀和寫 # 'U' universal newline mode (deprecated) #  # xxx。txt 寫入時,使用得utf8編碼格式 # 在windows操作系統里,默認使用gdk 編碼格式打開文件 # open 函數會有一個返回值 , 打開的文件對象 # 解決方案 :寫入和讀取 使用相同的編碼格式。 # 寫入用什么編碼格式寫,讀取也要同步

  -------# 文件句柄 = open()
file = open("xxx.txt",encoding='utf8') # print(type(file))
print(file.read()) open('xxx.txt',mode='r',encoding='utf8') re = open("xxx.txt", mode='r', encoding='utf8') print(re.read()) re.close() # readline
f= open('miaonan.txt',mode='r+',encoding='utf8') content = f.readline().strip() print(content) content = f.readline().strip() print(content) content = f.readline() print(content) t = f.tell() print(t) f.close() # ----- 寫 write
re = open('miaonan.txt',mode='w',encoding='utf8')     #
f = re.write('秒男'+"zhang")                           # 返回字符串得個數
re1 = open('miaonan.txt',mode='a',encoding='utf8')    # 追加寫
f1 = re1.write('nihao') print(f) re.close() # --- r+ w+ 指針 tell seek
f5 = open('miaonan.txt',mode='r+',encoding='utf8') re = f5.read(5) print(re) t = f5.tell() print(t) # f5.seek(5) // 改變指針位置
content = f5.read() print(content) f5.close() # ------ 讀取一個文件 -寫進一個新文件
f2 = open('miaonan.txt',encoding='utf8')      # 讀取一個文件內容
f3 = open('ooo',mode='w',encoding='utf8')     # 寫一個新文件
content = f2.read()                           # 去讀文件內容提取
f3.write(content)                             # 把 讀取內容寫進新文件里
f2.close() f3.close() # -----------文件的路徑 # import os #  # print(os.name) # NT/ posix # print(os.sep) # windows系統里,文件夾之間使用\ 分隔 # 在python 的字符串里 , \ 表示轉義字符 # 在Windows系統里 文件夾使用\分隔 # 在非Windows系統里 文件夾使用 / 分隔 #  # 路徑書寫的三種方式: 1. \\ 2.r'\' 3.'/'(推薦使用) #  # 路徑分為兩種: # 1.絕對路徑:從電腦盤符開始 # file = open('C:\\Users\\dell\\PycharmProjects\\jh_pyton 學習\\xxx.txt') # file = open(r'C:\Users\dell\PycharmProjects\jh_pyton 學習\xxx.txt') # file = open('C:/Users/dell/PycharmProjects/jh_pyton 學習/xxx.txt') #  # 2.相對路徑:當前文件所在的文件夾開始的路徑。 # file = open('xxx.txt') # # file = open('../')# ../返回上一級 # print(file.read())



# 讀圖片寫到另一個文件里邊
l = open("xxxd.jpg",mode='rb') re = open('bs.png', mode='wb') content = l.read() re.write(content) print(content) print(re) l.close() re.close() with open('ooo',mode='a+',encoding='utf8') as f1:     # 便捷打開文件方式
    for  i in f1: print(i) with open('xxxd.jpg',mode='rb') as fl,\ open('xxtt.jpg',mode='wb')as f2 : # content = fl.read()
    # f2.write(content)
    for i in fl: f2.write(i)

 


免責聲明!

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



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