I have created a script to write to a file in Python:
a_file = open("file:///C:/Users/xdo/OneDrive/Desktop/Javascript/read%20and%20write/testfileTryToOVERWRITEME.txt", "a+")
a_file.write("hello")
a_file.close()
The absolute path of the file is: file:///C:/Users/xdo/OneDrive/Desktop/Javascript/read%20and%20write/testfileTryToOVERWRITEME.txt
However, the program does not write (append) to the file. I can run the program, but nothing happens to the file. The strange thing is that it works if I put the file in the same directory as the script and run the script using the location testfileTryToOVERWRITEME.txt
. That is:
a_file = open("testfileTryToOVERWRITEME.txt", "a+")
a_file.write("hello")
a_file.close()
This works 100% and appends to the file. But when I use the absolute path of the file, it never works. What is wrong?
I also tried:
a_file = open("C:/Users/xdo/OneDrive/Desktop/Javascript/read%20and%20write/testfileTryToOVERWRITEME.txt", "a+")
a_file.write("hello")
a_file.close()
This did not work.
Try doing "with". Also, replace the %20
with a space. Python does not automatically decode this, but you shouldn't have an issue using spaces in the instance below.
with open("c:/users/xdo/OneDrive/Desktop/Javascript/read and write/testfile.txt", "a+") as file:
file.write("hello")
In this case, if the file doesn't exist, it will create it. The only thing that would stop this is if there are permissions issues.