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类似