Python - 读取并附加到文件

时间:2014-06-01 19:13:15

标签: python windows python-2.7

我有以下Python代码:

with open('helper.txt', 'a+') as f:
    lines = f.read().splitlines()
    for line in lines:
        print line
    f.write('new_line \n')

它首次在“helper.txt”文件中创建并写入“new_line \ n”,但由于某种原因第二次失败:

Traceback (most recent call last):
new_line
  File "E:/work/projects/src/helper/main.py", line 50, in main
    f.write('new_line \n')
IOError: [Errno 0] Error

为什么呢?我究竟做错了什么?我该如何解决?

btw我正在使用Python 2.7.6。

1 个答案:

答案 0 :(得分:1)

你需要寻求,这是有效的:

import os

with open('helper.txt', 'a+') as f:
    f.seek(0, os.SEEK_SET)
    for line in f:
        print line.strip()
    f.seek(0, os.SEEK_END)
    f.write('new_line \n')
相关问题