Started Python a week ago and I have some questions to ask about reading and writing to the same files. I've gone through some tutorials online but I am still confused about it. I can understand simple, working code to read and write files.:
openFile = open("filepath", "r")
readFile = openFile.read()
print (readFile )
openFile = open("filepath", "a")
appendFile = openFile.write("\nTest 123")
openFile.close()
But, if I try to read and write the followingsame file, I get a bunch of unknown text inerrors, or the resulting text file I am writing to. Can anyone explain why I am getting such errors and whyis not what I cannot use the same openFile object the way shown belowexpect. For example:
# I get an error when I use the codes below:
openFile = open("filepath", "r+")
writeFile = openFile.write("Test abc")
readFile = openFile.read()
print (readFile)
openFile.close()
Why can't I will try to clarify my problems. In the example above, openFile iswrite the object usedcode this way? It seems to open file. I have no problemswork if I want write to it the first time. If I want to use the samea separate openFile to read files or append something to it. It doesn't happen or an error is given. I have to declare the same/different open file object before I can perform another read/write action toopen
call for the same file.:
#I have no problems if I do this:
openFile = open("filepath", "r+")
writeFile = openFile.write("Test abc")
openFile2 = open("filepath", "r+")
readFile = openFile2.read()
print (readFile)
openFile.close()
I will be grateful if anyone can tell me what I did wrong here or is it just a Pythong thing. I am using Python 2.7. Thanks!