python - 如何在 Linux 上的 Python 中使用 open() 和追加模式以及eek()?

标签 python linux file seek

我有以下内容:

with open(file, 'a') as log:

   #A bunch of code, some of it writes to log.

   log.seek(0)
   log.write(time.strftime(t_format))

seek() 不适用于追加,如果我使用“w”,则文件的开头会被覆盖。在文档中它说,“...'a' 用于附加(在某些 Unix 系统上意味着所有写入都附加到文件末尾,无论当前的查找位置如何)”

有什么办法可以覆盖这个吗?

最佳答案

seek 的第二个参数允许相对于文件末尾进行查找:

with open(filename, 'w') as log:
    log.seek(0, 0)
    log.write(time.strftime(t_format))

您还应该考虑使用Python的日志记录模块来写入日志。

关于python - 如何在 Linux 上的 Python 中使用 open() 和追加模式以及eek()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26425988/

相关文章:

c - HTTP 通过 C 中的套接字 : Basic file server fails to properly return file

python - 我怎么知道为什么在 SQLAlchemy 中发生回滚?

python - 使用正则表达式查找长度为 4 的单词

linux - wget 找不到 .listing?

php - 百胜升级到 PHP 5.4?

c# - 将 varbinary 转换回 .txt 文件

python - 为什么 try-finally 有效,但 try-else-finally 无效?

python - 替换python 3中的第一个字符串字符

linux - Linux 中的 cakephp 热插拔驱动程序是否与 Windows 中的设备禁用/启用功能相同?

java - 删除多个文件 Java (Android)