实施网站推广的最终目的是北京推广优化公司
readline和readlines的区别
使用 open()读取文件时,readline是读取文件的一行;而readlines是加载全部文档,以list形式保存每一行内容。
使用with避免资源泄露
with语句不仅限于open()函数,任何实现了上下文管理协议的对象都可以使用以确保发生异常时,资源也能被正确释放。
安全读取文件
多用户系统中的文件通常归属于不同用户,用户可指定访问的内容。
文件创建时规定了哪些用户可以访问或者操作这个文件。
import os import statflags = os.O_WRONLY | os.O_CREAT | os.O_EXCL # 改变os的常量设置相应文件读写方式。 modes = stat.S_IWUSR | stat.S_IRUSR with os.fdopen(os.open('test.txt', flags, modes), 'w') as f:f.write('secrets!')
读取文件的其他方法
from pathlib import Pathfile_path = Path("./data/new_text.txt") file_path.touch(exist_ok=True) # 创建空文件 with file_path.open("w", encoding="utf-8") as file:file.write("Using PathLib\n")# 创建临时文件 import tempfilewith tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', delete=False) as temp_file:temp_file.write("This is a temporary file\n")temp_file_name = temp_file.name print(f"Temporary file created: {temp_file_name}")
文件锁定
import fcntlwith open('./data/new_text.txt', "r+") as file: # 打开文件获取独占锁fcntl.flock(file.fileno(), fcntl.LOCK_EX)file.seek(0) # 操作文件content = file.read()print(content)fcntl.flock(file.fileno(), fcntl.LOCK_UN) # 释放锁
参考:
https://www.51cto.com/article/792322.html