'Errno 2 No such file or directory in Python
I'm trying to run the following code but I keep getting this error every time I run it:
[Errno 2] No such file or directory: 'words_sorted.txt'
This is the code I'm trying to run but can't figure out how to not get this error. I have also attached the txt. file
#function definition
def words_with_letters(words, letters):
#if letters is empty string then return words list
if letters == "":
return words
#new list for storing all the subsequences
subseq = []
#iteration over the words list
for word in words:
index = 0
#iteration over the word string
for char in word:
#letter which is initialized to the first letter of letters string
letter = letters[index]
#if letter is found in the word string
if char == letter:
#updating the letter to next letter of the letters string
index += 1
#if end of letters is reached, adding the word to subsequences
if index == len(letters):
subseq.append(word)
break
return subseq
#creating empty list for storing the words in text file
words = []
#opening the text file in the read mode
with open("words_sorted.txt") as file:
#iterating over the file object
for line in file:
#removing the newline character from the line and adding word to the words list
word = line.strip()
words.append(word)
Solution 1:[1]
The error is saying that the file cannot be found, you probably knew that. That usually happens when you are running the code from a different folder than the one holding the file. It doesn't seem to be related to the code at all and therefore I won't be able to replicate the error unless you can show us where is your Python file and where is "words_sorted.txt". If both of the files are in the same directory it should work fine. If the txt file is in another folder, you can just use the full path to open the file:
path = 'C:/path/to/file.txt'
with open(path) as file:
...
In any case, I recommend you to learn about how directories work in Python and how you can manage them, for example, appending directories to your path (using sys.path.append) or using relative paths. This can give you some insight:
https://www.programiz.com/python-programming/directory
Python: Best way to add to sys.path relative to the current running script
Also, I don't understand why you included the words_with_letters function in the post, it seems completely unrelated to the topic unless what you pasted is your file, in which case you should try to be cleaner with your code, maybe start using the main function and stuff like that.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dharman |
