文件是否存在
1. 文件或目录是否存在
os.path.exists("name")
2. 是否是文件
os.path.isfile("name")
是否有权限
os.access(path, mode)
1. path为文件路径
2. mode为操作模式:
os.F_OK: 检查文件是否存在
os.R_OK: 检查文件是否可读
os.W_OK: 检查文件是否可以写入
os.X_OK: 检查文件是否可以执行
删除文件
try:
os.remove(filePath)
except FileExistsError as e:
print(e)
打开文件
open时获取句柄,确定文件开始结束位置(还没读入内存)
close时写入硬盘,超过1024字节自动写入
1. open
def open_file(filePath):
f = None
try:
f = open(filePath, ‘r’, encoding=‘utf-8’)
print(f.read())
except FileNotFoundError:
print(‘无法打开指定的文件!’)
except LookupError:
print(‘指定了未知的编码!’)
except UnicodeDecodeError:
print(‘读取文件时解码错误!’)
except PermissionError:
print(‘权限不足!’)
except IOError:
print(‘IO错误!’)
except Exception:
print(‘其它错误!’)
finally:
if f is not None:
f.close()
2. with(自动回收资源)
with open(filePath, mode=‘r’, encoding=‘utf-8’) as f:
print(f.read())
文件操作模式
1. r:只读(默认)
2. w:只写(会覆盖之前的内容)
3. x:写入,如果文件已经存在会产生异常
4. a:追加,将内容写入到已有文件的末尾
5. b:二进制模式
6. t:文本模式(默认)
7. +:读写
读
1. 一次性读取整个文件内容(str)
with open(filePath, 'r') as f:
print(f.read())
2. 通过for-in循环逐行读取(str)
with open(filePath, 'r') as f:
for line in f:
print(line)
3. 按行读取到列表中(list)
with open(filePath, 'r') as f:
print( f.readlines())
写
1. write()
2. writelines() 写多行
光标
1. seek() 移动到指定位置
2. tell() 当前位置
3. truncate(n) 清空文件内容(只留下文件开头的n字节)