要保持文件的修改时间并添加内容,可以使用Python的os
模块和shutil
模块来实现。
import os
import shutil
def add_content_with_preserve_mtime(file_path, content):
# 获取文件的修改时间
mtime = os.path.getmtime(file_path)
# 创建一个临时文件
temp_file = file_path + ".temp"
try:
# 打开原文件和临时文件
with open(file_path, 'rb') as src_file, open(temp_file, 'wb') as temp:
# 复制原文件的内容到临时文件
shutil.copyfileobj(src_file, temp)
# 在临时文件末尾添加新内容
temp.write(content)
# 将临时文件重命名为原文件
os.rename(temp_file, file_path)
# 恢复文件的修改时间
os.utime(file_path, (mtime, mtime))
except Exception as e:
print("Error: ", e)
# 删除临时文件
if os.path.exists(temp_file):
os.remove(temp_file)
# 示例用法
file_path = "example.txt"
content = "This is some new content."
add_content_with_preserve_mtime(file_path, content)
上述代码的add_content_with_preserve_mtime
函数会将原文件的内容复制到一个临时文件中,然后在临时文件末尾添加新的内容。最后,将临时文件重命名为原文件,并使用os.utime
方法将文件的修改时间恢复为原来的时间。
请注意,这种方法只能在具有适当权限的操作系统中正常工作。在某些操作系统中,可能无法直接修改文件的修改时间。
下一篇:保持XPtr用于多个会话