简体   繁体   中英

Python Reopening file after writing it

I've already managed to create a program called write.py that accepts information via "post" from HTML and writes this information (only ever one line long) to a file called infoLog.ssv. Now I'm trying to create another .py program that will both append this document with another line of text, and then read everything that is contained within infoLog.ssv and print it to the screen. I seem to be running into issues when my program tries to open the appended file. I've checked and yes, my program is successfully appending the document, but it seems to just stop working when I reopen it.

f=open("infoLog.ssv","a")
strValueQuestion=str(question)
f.write("\n"+strValueQuestion)
f.close()
print "Successfully added"
f1=open("infoLog.ssv","r")
f1.close()
sys.stdout.flush()
print "It never prints this..."

As you can see, while attempting to debug, I only open and close the file now and even still it never prints the last print statement.

Check your logs, it is probably giving an error in the line f1.open("infoLog.ssv", "r") .

If you want to print the file contents, what you mean is probably:

with open("infoLog.ssv","r") as f1:
    print f1.read()
    sys.stdout.flush()
    print "It should prints this... =)"

Note that if you use the with statement, you don't need to explicitly close the file descriptor .

Apparently 'r+' or 'w+' allow you to both read and write to a file at the same time. https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM