Python 文件操作

1.文件的打开与关闭

文件的打开采用open()函数,文件的关闭采用close()函数。

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None):

file:一个字符串表示的文件名称,或者一个数组表示的文件名称。文件名称可以是相对当前目录的路径,也可以是绝对路径表示。

mode:指明打开文件的模式,默认值是'r'。

字符含义
'r' 打开阅读(默认)
'w' 打开写入,首先截断文件
'x' 打开以供独占创建,如果文件已存在则失败
'a' 打开以供写入,如果存在,则附加到文件的末尾
'b' 二进制模式
't' 文本模式(默认)
'+' 打开磁盘文件进行更新(读写)
'U' 通用换行符模式(已弃用)

encoding:用于解码或编码文件的编码的名称,如:‘utf-8'

其他参数不常用就不讲解了。

close():当你使用完一个文件时,调用 close() 方法就可以关闭它并释放其占用的所有系统资源。

f.close()

文件打开关闭示例:

f=open('text.log','r',encoding= 'utf-8')
f.close()

with语句:
为了避免打开文件后忘记关闭,可以通过管理上下文来文件管理,如:

with open('text.log','r',encoding= 'utf-8') as file_ex :
    print(file_ex.read())
    pass

也可以同时对多个文件进行文件管理,如:

with open('text.log','r',encoding= 'utf-8') as file_ex ,open('text2.log','r',encoding= 'utf-8') as file_ex2 :
    pass

2.文件的读写操作

3.文件的其他操作

原文地址:https://www.cnblogs.com/olivexiao/p/6533083.html