So I have been trying to write a text file in a specific directory with the following code (note_value and note_title are variables already set to a string) :
file = open("resources/user_notes/" + note_title + ".txt", "w")
file.write(note_value)
file.close()
When I try this I get the following error :
file = open("resources/user_notes/" + note_title + ".txt", "w")
FileNotFoundError: [Errno 2] No such file or directory: 'resources/user_notes/the.txt'
The directory I am using does exist, I have even copied the directory path from my file explorer to python, and it still doesn't work. If you know the solution to this please let me know.
Have you tried with joining?
import os
fn = os.path.join(os.path.dirname(__file__), '/resources/user_notes/the.txt')
with open(fn, 'r') as readfile:
for line in readfile:
print(line)
I encountered a similar problem while writing to multiple text files from Python. Most of the files had no issue, but a few resulted in
FileNotFoundError: [Errno 2] No such file or directory: 'IO/INDUSTRIES.txt'
Turns out the "/" in filename was causing the issue. This means that due to "/" my filename is "INDUSTRIES.txt" which resides in the "IO" folder, which is not true. So removing the "/" resolves this issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With