Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python——读取并附加到文件中_Python_Windows_Python 2.7 - Fatal编程技术网

Python——读取并附加到文件中

Python——读取并附加到文件中,python,windows,python-2.7,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') 它第一次创建“new\u line\n”并将其写入“helper.txt”文件,但由于某些原因第二次失败: Traceback (most recent call last): new_lin

我有以下Python代码:

with open('helper.txt', 'a+') as f:
    lines = f.read().splitlines()
    for line in lines:
        print line
    f.write('new_line \n')
它第一次创建“new\u line\n”并将其写入“helper.txt”文件,但由于某些原因第二次失败:

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
为什么??我做错了什么?我怎样才能修好它


顺便说一句,我使用的是Python 2.7.6。

您需要查找,它可以:

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')

顺便说一句,你的代码可以在linux上运行。此行为可能特定于windows。文档中提到了与
mode=a+
的区别。此外,您可以摆脱
f.read().splitlines()
,只需对f中的行执行
:…
为什么将此模式命名为“a+”(append)然后?
lines=f.read().splitlines();for line in line
与for line in f相同,只是前者对于大文件占用大量内存。@Adam Smith是的,但为什么我需要在这种情况下手动使用seek?for line in f:将输出两次换行,而splitline()只输出一次。不会为f中的行输出相同的。@MarinovIván for
:print line.strip()