Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a FileNotFoundError for writing a text file

Tags:

python

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.

like image 503
Jak Avatar asked Nov 27 '25 12:11

Jak


2 Answers

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)
like image 176
mutantkeyboard Avatar answered Nov 30 '25 01:11

mutantkeyboard


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.

like image 43
fam Avatar answered Nov 30 '25 00:11

fam