0

I can't make my code work. I open the file with r+ attribute, print what's already in it, take 2 lines from the user, but cannot write these files:

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

All I get is:

Traceback (most recent call last):

File "C:/Python27/new.py", line 10, in

file1.write(line1)

IOError: [Errno 0] Error

Community
  • 1
  • 1
Maicon Erick
  • 127
  • 1
  • 11
  • 1
    You opened `file1` for reading (`"r+"`). You cannot write into it. Asd a side note, `file1.read()` reads the whole file, to the end. The next time you call it, it reads nothing, because everything has been already read. – DYZ Jun 03 '17 at 03:31
  • Use `w` or `wb` – Mangohero1 Jun 03 '17 at 03:33
  • From the doc: `r+ opens the file for both reading and writing.` – Maicon Erick Jun 03 '17 at 03:34
  • @mangoHero1 Both `w` and `wb` gives me this error: `Traceback (most recent call last): File "C:/Python27/new.py", line 4, in print file1.read() IOError: File not open for reading` – Maicon Erick Jun 03 '17 at 03:41
  • @mangoHero1 `w` creates a new file. From the doc: ´'w' for only writing (an existing file with the same name will be erased)´ – Maicon Erick Jun 03 '17 at 03:43
  • @Ed Morton I couldn't use any other tags besides the recommended ones. I had to use 2. – Maicon Erick Jun 03 '17 at 03:44

2 Answers2

0

after you read and write the lines, you cannot do file1.read() again because you are starting that from the end of the file!

your last 3 lines should look like this:

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

but even more recommended is that you read and write on separate occasions, try this code:

    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()
Ofer Sadan
  • 11,391
  • 5
  • 38
  • 62
  • Okay, but I can't write. The error is when I try to write the `line1` – Maicon Erick Jun 03 '17 at 03:37
  • Yes, I do believe the error within your code is your first `.read()` call. Try moving that to the end of your code and you should be fine. – Mangohero1 Jun 03 '17 at 04:02
  • If I add the ´.read()´ at the end, my txt file gets floodered with random data like: ´sb d Z d d l m Z d d d „ ƒ YZ e d k r^ d d l m Z e d d d d e ƒn d S( s9 Implement Idle Shell history mechanism with History classiÿÿÿÿ( t idleConft Historyc B s; e Z d Z d „ Z d „ Z d „ Z d „ Z d „ Z RS( s@ Implement Idle Shell history mechanism. store - Store source statement (called from PyShell.resetoutput)..´ – Maicon Erick Jun 03 '17 at 04:31
  • Your code gives me this `Traceback (most recent call last): File "C:/Python27/a.py", line 11, in print f.read() ValueError: I/O operation on closed file` – Maicon Erick Jun 03 '17 at 04:33
0

Tested code:

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

Output:

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

Assumes you have a \n at end of the file but that's the only condition.

Recommend you read this for more python file IO modes.

pstatix
  • 3,611
  • 4
  • 18
  • 40