【Python】File

打开文件

file = open(filename, mode[…])

open()函数至少两个参数,文件名可以是文件实际名字也可以是包含完整路径的名字

open()函数返回一个文件对象,使用该文件对象可以进行读写操作

eg. rt表示打开文本文件,rb表示打开二进制文件

文本文件若用二进制形式打开,显示的是编码

1
file = open("test.py", "rt", encoding="utf-8")

如果文件名包含路径,比如D:\python\test.py

1
2
3
4
file = open(r"D:\python\test.py", "r")
file = open("D:\\python\\test.py", "r")
file = open("D:/python/test.py", "r")
#不可以直接file = open("D:\python\test.py"),因为\会被当成转义字符

关闭文件

file.close()

如果前面用的是with open则不用close()

文件读写操作

file为文件对象

1
2
3
4
5
6
7
8
9
f = open(fname, w+) #如果有文件则覆盖写,没有文件则创建
l = [1,2,3]
f.writelines(l)
print(f.tell()) #文件指针所在位置,这里是3(即文件末尾)
f.seek(0) #把文件指针放回到开头位置
print(f.tell()) #输出0
for line in f:
print(line) #输出123
f.close()