user197010
user197010

Reputation: 35

In python why it won't print without newline

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

Upvotes: 3

Views: 287

Answers (1)

TheoretiCAL
TheoretiCAL

Reputation: 20581

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)

Upvotes: 7

Related Questions