Python basics - why is the contents of the contents of my file not content?

I run this from eclipse, the name of the file I'm working with is ex16_text.txt (yes, I type it correctly. It writes the file correctly (input appears), but "print txt.read ()" does nothing (prints blank line), see the output after the code:

filename = raw_input("What the file name we'll be working with?")

print "we're going to erase %s" % filename

print "opening the file"
target = open(filename, 'w')

print "erasing the file"
target.truncate()

print "give me 3 lines to replace file contents:"

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "writing lines to file"

target.write(line1+"\n")
target.write(line2+"\n")
target.write(line3)

#file read
txt = open(filename)

print "here are the contents of the %s file:" % filename
print txt.read()

target.close()

Conclusion:

What file name will we work with? ex16_text.txt we will delete ex16_text.txt opening the file erasing the file give me 3 lines to replace the contents of the file: line 1: three line 2: two line 3: one record of lines in the file here is the contents of the file ex16_text.txt:

+3
source share
2 answers
target.write(line2+"\n")
target.write(line3)
target.close() #<------- You need to close the file when you're done writing.
#file read
txt = open(filename)
+4
source

flush , , , . :

: flush() . flush(), os.fsync(), .

, , . , - , .

Python 2.6 with :

with open(filename, 'w') as target:
    target.write('foo')
    # etc...

# The file is closed when the control flow leaves the "with" block

with open(filename, 'r') as txt:
    print txt.read()
+6

Source: https://habr.com/ru/post/1774421/


All Articles