Python讀寫文件基礎.py


基本函數

定義

python內置了open()函數來操作文件,open()函數的定義為:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised.

file is a path-like object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed, unless closefd is set to False.)

mode is an optional string that specifies the mode in which the file is opened. It defaults to 'r' which means open for reading in text mode. Other common values are 'w' for writing (truncating the file if it already exists), 'x' for exclusive creation and 'a' for appending (which on some Unix systems, means that all writes append to the end of the file regardless of the current seek position). In text mode, if encoding is not specified the encoding used is platform dependent: locale.getpreferredencoding(False) is called to get the current locale encoding. (For reading and writing raw bytes use binary mode and leave encoding unspecified.) The available modes are:

操作模式

Character Meaning
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' open for exclusive creation, failing if the file already exists
'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 newlines mode (deprecated)

讀操作

直接讀取

要注意在使用完后需要close

#讀取文件
    def readDemo1(self):
        #以只讀模式打開文件,如果打開失敗有error輸出
        try:
            f = open('D:\\readfiledemo.txt', 'r')
            print(f.read())
        #要用finally來關閉文件!
        finally:
            if f:
                f.close()

更簡潔的讀取

使用with的方式可以避免忘記close

def readDemo2(self):
        try:
            #使用with的方式可以不用主動close
            with open('D:\\readfiledemo.txt', 'r') as f:
                print(f.read())
        except:
            pass

按照行讀取

上面的操作方式如果是文件太大那么直接程序就異常或者崩潰,並且通常使用時候按照行讀取也更為實用

def readDemo3(self):
        try:
            with open('D:\\readfiledemo.txt', 'r') as f:
                #按照行讀取
                for line in f.readlines():
                    #去除行尾的\n
                    print(line.strip())
        except:
            pass

讀取二進制文件:

#二進制的方式讀取,例如圖片音樂文件等
    def readDemo4(self):
        try:
            #一次性的讀取,文件太大就會崩潰了!!!
            with open('D:\\error.bak', 'rb') as f:
                print(f.read())
        except:
            pass

以指定編碼字符集來讀取

通常很多文件有編碼字符集的要求,如果不使用指定格式那么就會有亂碼。如果不需要提示異常那么直接配置為忽略模式即可

#指定字符集的方式讀取,並且忽略錯誤
    def readDemo5(self):
        try:
            with open('D:\\example.log', 'r', encoding='utf-8', errors='ignore') as f:
                #按照行讀取
                for line in f.readlines():
                    #去除行尾的\n
                    print(line.strip())
        except:
            pass

寫操作

寫操作和讀操作基本上一致,需要注意的有兩點:

  • 如果使用的是非with的方式,那么要注意在close操作中才會寫入文件,否則是沒有提交的
  • 寫的時候要注意模式是追加還是覆蓋
def wirteDemo1(self):
        try:
            #w:覆蓋式寫入
            #a:追加式寫入
            with open('D:\\example.log', 'w', encoding='utf-8', errors='ignore') as f:
                f.write('this a 例子')
                f.write('\rthis a 例子 追加')
        except:
            pass

內存讀寫

內存讀寫通過StringIO和BytesIO來操作,前者操作字符流,后者操作二進制流。使用和open類似


免責聲明!

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



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