3

I am new to learning python. I don't understand why print command will output all variables on screen but write command to file only writes 2 first two variables.

print "Opening the file..."
target = open(filename, 'a+')

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
line4 = line1 + "\n" + line2 + "\n" + line3

# This command prints all 3 (line1,line2,line3) variables on terminal
print line4

#This command only writes line1 and line2 variables in file
target.write(line4)

print "close the file"
target.close()
user197010
  • 35
  • 4

1 Answers1

7

The OS normally flushes the write buffer after a newline. When you open(filename, 'a+') the file, these same rules apply by default.

From the docs: https://docs.python.org/2/library/functions.html#open

The optional buffering argument specifies the file’s desired buffer size: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (approximately) that size (in bytes). A negative buffering means to use the system default, which is usually line buffered for tty devices and fully buffered for other files. If omitted, the system default is used.

Call target.close() to ensure everything is written out ("flushed") to the file (as per the comment below, close flushes for you). You can manually flush with target.flush().

print "Opening the file..."
target = open(filename, 'a+')

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
line4 = line1 + "\n" + line2 + "\n" + line3

# This command prints all 3 (line1,line2,line3) variables on terminal
print line4

target.write(line4)

target.close() #flushes

Alternatively, using the with keyword will automatically close the file when we leave the with block: (see What is the python keyword "with" used for?)

print "Opening the file..."
with open(filename, 'a+') as target:

   line1 = raw_input("line 1: ")
   line2 = raw_input("line 2: ")
   line3 = raw_input("line 3: ")
   line4 = line1 + "\n" + line2 + "\n" + line3

   # This command prints all 3 (line1,line2,line3) variables on terminal
   print line4

   target.write(line4)
Community
  • 1
  • 1
TheoretiCAL
  • 19,461
  • 8
  • 43
  • 65
  • 4
    `close` autoflushes, so you usually don't need to `flush` yourself. – user2357112 Nov 02 '16 at 21:25
  • 2
    I think you should add a comment about `with` – Francisco Nov 02 '16 at 21:31
  • Forgot to mention that I already included close at the end but it still prints only line1 and line2 variable to file. Tried `with open(filename, 'a+') as target:` but same result. Can anyone explain this in layman. – user197010 Nov 03 '16 at 14:41
  • Did you wait a couple seconds before checking the file? After you write/close, your guaranteed the OS has the full data to write to disk, but it may not actually write it out for a couple seconds. – TheoretiCAL Nov 03 '16 at 23:46