python进行文件操作,在日常编程中是很常用的。为了方便大家,这里对各种文件操作的知识进行汇总。
一、文件的打开和关闭
open()函数
f1 = open(r’d:\测试文件.txt’, mode=‘r’, encoding=‘utf-8’)
content = f1.read()
print(content)
f1.close()
with open(r’d:\测试文件.txt’, mode=‘r’, encoding=‘utf-8’) as f1:
content = f1.read()
print(content)
open()内置函数,open底层调用的是操作系统的接口。
f1变量,又叫文件句柄,通常文件句柄命名有f1,fh,file_handler,f_h,对文件进行的任何操作,都得通过文件句柄.方法的形式。
encoding:可以不写。不写参数,默认的编码本是操作系统默认的编码本。windows默认gbk,linux默认utf-8,mac默认utf-8。
mode:可以不写。默认mode=‘r’。
f1.close()关闭文件句柄。
使用with open()的好处。
优点1:不用手动关闭文件句柄。
with open(‘文件操作的读’, encoding=‘utf-8’) as f1:
print(f1.read())
优点2:一个语句可以操作多个文件句柄。
with open(‘文件操作的读’, encoding=‘utf-8’) as f1,
open(‘文件操作的写’, encoding=‘utf-8’, mode=‘w’) as f2:
print(f1.read())