尝试向txt添加行时出错

时间:2017-06-03 03:28:00

标签: python

我不能让我的代码工作。 我用r +属性打开文件,打印已经存在的文件,从用户那里取2行,但不能写这些文件:

file1 = open('test.txt', 'r+')
print "\n This is your file:\n"
print file1.read()
print "Now type in 2 lines:"
line1 = raw_input("Line 1: ")
line2 = raw_input("Line 2: ")
print "Writing the lines"
file1.write(line1)
file1.write("\n")
file1.write(line2)
file1.write("\n")
print "\n This is your file again:\n"
print file1.read()
file1.close()

我得到的只是:

  

追踪(最近一次呼叫最后一次):

     

文件“C:/Python27/new.py”,第10行,

     

file1.write(line1)

     

IOError:[Errno 0]错误

2 个答案:

答案 0 :(得分:0)

在读取和写入行之后,你不能再次执行file1.read(),因为你是从文件的末尾开始的!

你的最后3行应如下所示:

    file1.seek(0) # go back to the start of the file
    print file1.read()
    file1.close()

但更推荐的是你在不同的场合读写,试试这段代码:

    with open('file1.txt') as f:
        print f.read()
    print 'Now write 2 lines'
    line1 = raw_input('line1:')
    line2 = raw_input('line2:')
    print 'Writing lines'
    with open('file1.txt','a') as f:
        f.write(line1 + '\n' + line2 + '\n')
    with open('file1.txt') as f:
        print 'This is your file again:'
        print f.read()

答案 1 :(得分:0)

经过测试的代码:

def func():
    with open('E:/test.txt', 'r') as f:
        print f.read()
    print "Now write 2 lines."
    l1 = raw_input("Line 1: ")
    l2 = raw_input("Line 2: ")
    with open('E:/test.txt', 'a') as f:
        f.write(l1 + "\n" + l2 + "\n")
    with open('E:/test.txt', 'r') as f:
        print ("This is your file now:\n" +
               f.read())

输出:

>>> func()
hey
therecoolguy
Now write 2 lines.
Line 1: cool
Line 2: guy
This is your file now:
hey
there
cool
guy

假设您在文件末尾有\n,但这是唯一的条件。

建议您阅读this了解更多python文件IO模式。