I’m trying to write a simple program to read a file and search for a word then print how many times that word is found in the file. Every time I type in «test.rtf» (which is the name of my document) I get this error:
Traceback (most recent call last):
File "/Users/AshleyStallings/Documents/School Work/Computer Programming/Side Projects/How many? (Python).py", line 9, in <module>
fileScan= open(fileName, 'r') #Opens file
FileNotFoundError: [Errno 2] No such file or directory: 'test.rtf'
In class last semester, I remember my professor saying you have to save the file in a specific place? I’m not sure if he really said that though, but I’m running apple OSx if that helps.
Here’s the important part of my code:
fileName= input("Please enter the name of the file you'd like to use.")
fileScan= open(fileName, 'r') #Opens file
![]()
mkrieger1
16.9k4 gold badges51 silver badges58 bronze badges
asked Jul 15, 2013 at 16:13
1
If the user does not pass the full path to the file (on Unix type systems this means a path that starts with a slash), the path is interpreted relatively to the current working directory. The current working directory usually is the directory in which you started the program. In your case, the file test.rtf must be in the same directory in which you execute the program.
You are obviously performing programming tasks in Python under Mac OS. There, I recommend to work in the terminal (on the command line), i.e. start the terminal, cd to the directory where your input file is located and start the Python script there using the command
$ python script.py
In order to make this work, the directory containing the python executable must be in the PATH, a so-called environment variable that contains directories that are automatically used for searching executables when you enter a command. You should make use of this, because it simplifies daily work greatly. That way, you can simply cd to the directory containing your Python script file and run it.
In any case, if your Python script file and your data input file are not in the same directory, you always have to specify either a relative path between them or you have to use an absolute path for one of them.
![]()
wjandrea
26.2k8 gold badges56 silver badges77 bronze badges
answered Jul 15, 2013 at 16:17
0
Is test.rtf located in the same directory you’re in when you run this?
If not, you’ll need to provide the full path to that file.
Suppose it’s located in
/Users/AshleyStallings/Documents/School Work/Computer Programming/Side Projects/data
In that case you’d enter
data/test.rtf
as your file name
Or it could be in
/Users/AshleyStallings/Documents/School Work/Computer Programming/some_other_folder
In that case you’d enter
../some_other_folder/test.rtf
answered Jul 15, 2013 at 16:18
![]()
Jon KiparskyJon Kiparsky
7,3942 gold badges22 silver badges38 bronze badges
0
A good start would be validating the input. In other words, you can make sure that the user has indeed typed a correct path for a real existing file, like this:
import os
fileName = input("Please enter the name of the file you'd like to use.")
while not os.path.isfile(fileName):
fileName = input("Whoops! No such file! Please enter the name of the file you'd like to use.")
This is with a little help from the built in module os, That is a part of the Standard Python Library.
![]()
wjandrea
26.2k8 gold badges56 silver badges77 bronze badges
answered Jul 15, 2013 at 16:27
1
As noted above the problem is in specifying the path to your file.
The default path in OS X is your home directory (/Users/macbook represented by ~ in terminal …you can change or rename the home directory with the advanced options in System Preferences > Users & Groups).
Or you can specify the path from the drive to your file in the filename:
path = "/Users/macbook/Documents/MyPython/"
myFile = path + fileName
You can also catch the File Not Found Error and give another response using try:
try:
with open(filename) as f:
sequences = pick_lines(f)
except FileNotFoundError:
print("File not found. Check the path variable and filename")
exit()
answered Sep 28, 2018 at 11:12
You might need to change your path by:
import os
path=os.chdir(str('Here_should_be_the_path_to_your_file')) #This command changes directory
This is what worked for me at least! Hope it works for you too!
answered Feb 19, 2021 at 7:55
RandML000RandML000
111 silver badge4 bronze badges
Difficult to give code examples in the comments.
To read the words in the file, you can read the contents of the file, which gets you a string — this is what you were doing before, with the read() method — and then use split() to get the individual words.
Split breaks up a String on the delimiter provided, or on whitespace by default. For example,
"the quick brown fox".split()
produces
['the', 'quick', 'brown', 'fox']
Similarly,
fileScan.read().split()
will give you an array of Strings.
Hope that helps!
answered Jul 15, 2013 at 16:52
![]()
Jon KiparskyJon Kiparsky
7,3942 gold badges22 silver badges38 bronze badges
0
First check what’s your file format(e.g: .txt, .json, .csv etc ),
If your file present in PWD , then just give the name of the file along with the file format inside either single(»)or double(«») quote and the appropriate operation mode as your requirement
e.g:
with open('test.txt','r') as f: data=f.readlines() for i in data: print(i)
If your file present in other directory, then just give the full path name where is your file is present and file name along with file format of the file inside either single(»)or double(«») quote and the appropriate operation mode as your requirement.
If it showing unicode error just put either r before quote of file path or else put ‘/’ instead of »
with open(r'C:UserssomanDesktoptest.txt','r') as f: data=f.readlines() for i in data: print(i)
answered Nov 3, 2021 at 7:08
The mistake I did was
my code :
x = open('python.txt')
print(x)
But the problem was in file directory ,I saved it as python.txt instead of just python .
So my file path was
->C:UsersnoobDesktopPythonCourse 2python.txt.txt
That is why it was giving a error.
Name your file without .txt it will run.
![]()
Jamiu S.
5,2554 gold badges8 silver badges31 bronze badges
answered Aug 14, 2020 at 16:37
Разрабатывая приложения вам придется работать с файлами, анализировать большие объемы данных, сохранять пользовательские данные, чтобы они не терялись по завершению работы программы. Также при работе с файлами важно научиться обрабатывать ошибки, чтобы они не привели к аварийному завершению программы. Для этого в Python существуют специальные объекты — исключения, которые создаются для управления ошибок.
| Содержание страницы: |
|---|
| 1. Чтение файла |
| 1.2. Чтение больших файлов и работа с ними |
| 1.3. Анализ текста из файла |
| 2. Запись в файл |
| 2.1. Запись в пустой файл |
| 2.2. Многострочная запись в файл |
| 2.3. Присоединение данных к файлу |
| 3. Исключения |
| 3.1. Блоки try-except |
| 3.2. Блоки try-except-else |
| 3.3. Блоки try-except с текстовыми файлами |
| 3.4. Ошибки без уведомления пользователя |
1. Чтение файла в Python
В файлах может содержаться любой объем данных, начиная от небольшого рассказа и до сохранения истории погоды за столетия. Чтение файлов особенно актуально для приложений, предназначенных для анализа данных. Приведем пример простой программы, которая открывает файл и выводит его содержимое на экран. В примере я буду использовать файл с числом «Пи» с точностью до 10 знаков после запятой. Скачать этот файл можно прямо здесь ( pi_10.txt ) или самим создать текстовый файл и сохранить под любым именем. Пример программы, которая открывает файл и выводит содержимое на экран:
with open(‘pi_10.txt’) as file_pi:
digits = file_pi.read()
print(digits)
Код начинается с ключевого слова with. При использование ключевого слова with используемый файл открывается с помощью функции open(), а закрывается автоматически после завершения блока with и вам не придется в конце вызывать функцию close(). Файлы можно открывать и закрывать явными вызовами open() и close(). Функция open() получает один аргумент — имя открываемого файла, в нашем случае ‘pi_10.txt’. Python ищет указанный файл в каталоге, где хранится файл текущей программы. Функция open() возвращает объект, представляющий файл ‘pi_10.txt’. Python сохраняет этот объект в переменной file_pi .
После появления объекта, представляющего файл ‘pi_10.txt’, используется метод read(), который читает все содержимое файла и сохраняет его в одной строке в переменной contents. В конце с помощью функции print содержимое выводится на экран. Запустив этот файл, мы получим данные, находящиеся в нашем файле ‘pi_10.txt’.
3.1415926535
В случае, если файл расположен не в одном каталоге с файлом программы, необходимо указать путь, чтобы Python искал файлы в конкретном месте. Существует два пути как прописать расположение файла:
-
Относительный путь.
Относительный путь приказывает Python искать файлы в каталоге, который задается относительно каталога, в котором находится текущий файл программы
with open(‘files/имя_файла.txt’) as file:
-
Абсолютный путь.
Местонахождение файла не зависит от того, где находится ваша программа. Абсолютные пути обычно длиннее относительных, поэтому их лучше сохранить в переменную и затем передать функции open().
file_path = ‘/Users/Desktop/files/имя_файла.txt’
with open(file_path) as file:
С абсолютными путями можно читать файлы из любого каталога вашей системы.
1.2. Чтение больших файлов на Python и работа с ними
В первом примере был файл с 10 знаками после запятой. Теперь давайте проанализируем файл с миллионом знаков числа «Пи» после запятой. Скачать число «Пи» с миллионом знаков после запятой можно отсюда( ‘pi_1000000.txt’ ). Изменять код из первого примера не придется, просто заменим файл, который должен читать Python.
Выведем на экран первые 100 знаков после запятой. Добавим в конец функцию len, чтобы узнать длину файла
3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679
1000002
Из выходных данных видно, что строка содержит значение «Пи» с точностью до 1 000 000 знаков после запятой. В Python нет никаких ограничений на длину данных, с которыми можно работать, единственное ограничение это объем памяти вашей системы.
После сохранения данных в переменной можно делать с ними все что угодно. Давайте проверим, входит ли в число «Пи» дата вашего дня рождения. Напишем небольшую программу, которая будет читать файл и проверять входит ли дата день рождения в первый миллион числа «Пи»:
with open(‘pi_1000000.txt‘) as file_pi:
digits = file_pi.read()
birthday = input(«Введите дату дня рождения: «)
if birthday in digits:
print(«Ваш день рождение входит в число ‘Пи'»)
else:
print(«Ваш день рождение не входит в число ‘Пи'»)
Начало программы не изменилось, читаем файл и сохраняем данные в переменной digits. Далее запрашиваем данные от пользователя с помощью функции input и сохраняем в переменную birstday. Затем проверяем вхождение birstday в digits с помощью команды if-else. Запустив несколько раз программу, получим результат:
Введите дату дня рождения: 260786
Ваш день рождение не входит в число ‘Пи’
Введите дату дня рождения: 260884
Ваш день рождение входит в число ‘Пи’
В зависимости от введенных данных мы получили результат вхождения или не вхождения дня рождения в число «Пи»
Важно: Читая данные из текстового файла, Python интерпретирует весь текст как строку. Если вы хотите работать с ним в числовом контексте, то преобразуйте данные в целое число функцией int() или в вещественное число функцией float().
1.3. Анализ текста из файла на Python
Python может анализировать текстовые файлы, содержащие целые книги. Возьмем книгу «Алиса в стране чудес» и попробуем подсчитать количество слов в книге. Текстовый файл с книгой можете скачать здесь(‘ alice ‘) или загрузить любое другое произведение. Напишем простую программу, которая подсчитает количество слов в книге и сколько раз повторяется имя Алиса в книге.
filename = ‘alice.txt’
with open(filename, encoding=’utf-8′) as file:
contents = file.read()
n_alice = contents.lower().count(‘алиса’)
words = contents.split()
n_words = len(words)
print(f»Книга ‘Алиса в стране чудес’ содержит {n_words} слов.»)
print(f»Имя Алиса повторяется {n_alice} раз.»)
При открытии файла добавился аргумент encoding=’utf-8′. Он необходим, когда кодировка вашей системы не совпадает с кодировкой читаемого файла. После чтения файла, сохраним его в переменной contents.
Для подсчета вхождения слова или выражений в строке можно воспользоваться методом count(), но прежде привести все слова к нижнему регистру функцией lower(). Количество вхождений сохраним в переменной n_alice.
Чтобы подсчитать количество слов в тексе, воспользуемся методом split(), предназначенный для построения списка слов на основе строки. Метод split() разделяет строку на части, где обнаружит пробел и сохраняет все части строки в элементах списка. Пример метода split():
title = ‘Алиса в стране чудес’
print(title.split())
[‘Алиса’, ‘в’, ‘стране’, ‘чудес’]
После использования метода split(), сохраним список в переменной words и далее подсчитаем количество слов в списке, с помощью функции len(). После подсчета всех данных, выведем на экран результат:
Книга ‘Алиса в стране чудес’ содержит 28389 слов.
Имя Алиса повторяется 419 раз.
2.1. Запись в пустой файл в Python
Самый простой способ сохранения данных, это записать их в файл. Чтобы записать текс в файл, требуется вызвать open() со вторым аргументом, который сообщит Python что требуется записать файл. Пример программы записи простого сообщения в файл на Python:
filename = ‘memory.txt’
with open(filename, ‘w’) as file:
file.write(«Язык программирования Python»)
Для начала определим название и тип будущего файла и сохраним в переменную filename. Затем при вызове функции open() передадим два аргумента. Первый аргумент содержит имя открываемого файла. Второй аргумент ‘ w ‘ сообщает Python, что файл должен быть открыт в режиме записи. Во второй строчке метод write() используется для записи строки в файл. Открыв файл ‘ memory.txt ‘ вы увидите в нем строку:
Язык программирования Python
Получившийся файл ничем не отличается от любых других текстовых файлах на компьютере, с ним можно делать все что угодно.
Важно: Открывая файл в режиме записи ‘ w ‘, если файл уже существует, то Python уничтожит его данные перед возвращением объекта файла.
Файлы можно открывать в режимах:
- чтение ‘ r ‘
- запись ‘ w ‘
- присоединение ‘ a ‘
- режим как чтения, так и записи ‘ r+ ‘
2.2. Многострочная запись в файл на Python
При использовании функции write() символы новой строки не добавляются в записываемый файл:
filename = ‘memory.txt’
with open(filename, ‘w’) as file:
file.write(«Язык программирования Python»)
file.write(«Язык программирования Java»)
file.write(«Язык программирования Perl»)
В результате открыв файл мы увидим что все строки склеились:
Язык программирования PythonЯзык программирования JavaЯзык программирования Perl
Для написания каждого сообщения с новой строки используйте символ новой строки n
filename = ‘memory.txt’
with open(filename, ‘w’) as file:
file.write(«Язык программирования Pythonn«)
file.write(«Язык программирования Javan«)
file.write(«Язык программирования Perln«)
Результат будет выглядеть так:
Язык программирования Python
Язык программирования Java
Язык программирования Perl
2.3. Присоединение данных к файлу на Python
Для добавления новых данных в файл, вместо того чтобы постоянно перезаписывать файл, откройте файл в режиме присоединения ‘ a ‘. Все новые строки добавятся в конец файла. Возьмем созданный файл из раздела 2.2 ‘memory.txt’. Добавим в него еще пару строк.
filename = ‘memory.txt’
with open(filename, ‘a’) as file:
file.write(«Hello worldn»)
file.write(«Полет на лунуn»)
В результате к нашему файлу добавятся две строки:
Язык программирования Python
Язык программирования Java
Язык программирования Perl
Hello world
Полет на луну
3. Исключения в Python
При выполнении программ могут возникать ошибки, для управления ими Python использует специальные объекты, называемые исключениями. Когда в программу включен код обработки исключения, ваша программа продолжится, а если нет, то программа остановится и выведет трассировку с отчетом об исключении. Исключения обрабатываются в блоках try-except. С блоками try-except программы будут работать даже в том случае, если что-то пошло не так.
3.1. Блоки try-except на Python
Приведем пример простой ошибки деления на ноль:
print(7/0)
Traceback (most recent call last):
File «example.py», line 1, in <module>
print(7/0)
ZeroDivisionError: division by zero
Если в вашей программе возможно появление ошибки, то вы можете заранее написать блок try-except для обработки данного исключения. Приведем пример обработки ошибки ZeroDivisionError с помощью блока try-except:
try:
print(7/0)
except ZeroDivisionError:
print(«Деление на ноль запрещено»)
Команда print(7/0) помещена в блок try. Если код в блоке try выполняется успешно, то Python пропускает блок except. Если же код в блоке try создал ошибку, то Python ищет блок except и запускает код в этом блоке. В нашем случае в блоке except выводится сообщение «Деление на ноль запрещено». При выполнение этого кода пользователь увидит понятное сообщение:
Деление на ноль запрещено
Если за кодом try-except следует другой код, то Python продолжит выполнение программы.
3.2. Блок try-except-else на Python
Напишем простой калькулятор, который запрашивает данные у пользователя, а затем результат деления выводит на экран. Сразу заключим возможную ошибку деления на ноль ZeroDivisionError и добавим блок else при успешном выполнение блока try.
while True:
first_number = input(«Введите первое число: «)
if first_number == ‘q’:
break
second_number = input(«Введите второе число: «)
if second_number == ‘q’:
break
try:
a = int(first_number) / int(second_number)
except ZeroDivisionError:
print(«Деление на ноль запрещено»)
else:
print(f»Частное двух чисел равно {a}»)
Программа запрашивает у пользователя первое число (first_number), затем второе (second_number). Если пользователь не ввел » q « для завершения работы программа продолжается. В блок try помещаем код, в котором возможно появление ошибки. В случае отсутствия ошибки деления, выполняется код else и Python выводит результат на экран. В случае ошибки ZeroDivisionError выполняется блок except и выводится сообщение о запрете деления на ноль, а программа продолжит свое выполнение. Запустив код получим такие результаты:
Введите первое число: 30
Введите второе число: 5
Частное двух чисел равно 6.0
Введите первое число: 7
Введите второе число: 0
Деление на ноль запрещено
Введите первое число: q
В результате действие программы при появлении ошибки не прервалось.
3.3. Блок try-except с текстовыми файлами на Python
Одна из стандартных проблем при работе с файлами, это отсутствие необходимого файла, или файл находится в другом месте и Python не может его найти. Попробуем прочитать не существующий файл:
filename = ‘alice_2.txt’
with open(filename, encoding=’utf-8′) as file:
contents = file.read()
Так как такого файла не существует, Python выдает исключение:
Traceback (most recent call last):
File «example.py», line 3, in <module>
with open(filename, encoding=’utf-8′) as file:
FileNotFoundError: [Errno 2] No such file or directory: ‘alice_2.txt’
FileNotFoundError — это ошибка отсутствия запрашиваемого файла. С помощью блока try-except обработаем ее:
filename = ‘alice_2.txt’
try:
with open(filename, encoding=’utf-8′) as file:
contents = file.read()
except FileNotFoundError:
print(f»Запрашиваемый файл {filename } не найден»)
В результате при отсутствии файла мы получим:
Запрашиваемый файл alice_2.txt не найден
3.4. Ошибки без уведомления пользователя
В предыдущих примерах мы сообщали пользователю об ошибках. В Python есть возможность обработать ошибку и не сообщать пользователю о ней и продолжить выполнение программы дальше. Для этого блок try пишется, как и обычно, а в блоке except вы прописываете Python не предпринимать никаких действий с помощью команды pass. Приведем пример ошибки без уведомления:
ilename = ‘alice_2.txt’
try:
with open(filename, encoding=’utf-8′) as file:
contents = file.read()
except FileNotFoundError:
pass
В результате при запуске этой программы и отсутствия запрашиваемого файла ничего не произойдет.
Далее: Функции json. Сохранение данных Python
Назад: Классы в Python
Если вы получили сообщение об ошибке «FileNotFoundError: [WinError 2] Система не может найти указанный файл», это означает, что по указанному вами пути нет файла.
В этом руководстве мы узнаем, когда это вызывается программой, и как обрабатывать ошибку FileNotFoundError в Python.
Воссоздание ошибки
Давайте воссоздадим этот скрипт, где интерпретатор Python выдает FileNotFoundError.
В следующей программе мы пытаемся удалить файл, но мы предоставили путь, которого не существует. Python понимает эту ситуацию, как отсутствие файла.
import os
os.remove('C:workspacepythondata.txt')
print('The file is removed.')
В приведенной выше программе мы попытались удалить файл, находящийся по пути C:workspacepythondata.txt.
Консольный вывод:
C:workspacepython>dir data*
Volume in drive C is OS
Volume Serial Number is B24
Directory of C:workspacepython
22-02-2019 21:17 7 data - Copy.txt
20-02-2019 06:24 90 data.csv
2 File(s) 97 bytes
0 Dir(s) 52,524,586,329 bytes free
У нас нет файла, который мы указали в пути. Итак, при запуске программы система не смогла найти файл, что выдаст ошибку FileNotFoundError.
Как решить проблему?
Есть два способа обработки ошибки FileNotFoundError:
- Используйте try-except и обработайте FileNotFoundError.
- Убедитесь, что файл присутствует, и выполните соответствующую операцию с файлом.
В следующей программе мы использовали Try Except. Мы будем хранить код в блоке try, который может вызвать ошибку FileNotFoundError.
import os
try:
os.remove('C:/workspace/python/data.txt')
print('The file is removed.')
except FileNotFoundError:
print('The file is not present.')
Или вы можете проверить, является ли указанный путь файлом. Ниже приведен пример программы.
import os
if os.path.isfile('C:/workspace/python/data.txt'):
print('The file is present.')
else:
print('The file is not present.')
This div height required for enabling the sticky sidebar
- What Is the
FileNotFoundError: [WinError 2] The system cannot find the file specifiedin Python - Why Does
FileNotFoundError: [WinError 2] The system cannot find the file specifiedError Occur in Python - How to Fix
FileNotFoundError: [WinError 2] The system cannot find the file specifiedin Python - Conclusion
![FileNotFoundError: [WinError 2] the System Cannot Find the File Specified](https://www.delftstack.com/img/Python/feature%20image%20-%20filenotfounderror%20[winerror%202]%20the%20system%20cannot%20find%20the%20file%20specified.png)
If you’re facing the FileNotFoundError in your Python program, the Python compiler cannot locate a file you’re trying to open.
It can happen for several reasons, such as if the file doesn’t exist, if the file is in a different directory than where your Python program is running, or if the file has a different name than what you expect.
What Is the FileNotFoundError: [WinError 2] The system cannot find the file specified in Python
The FileNotFoundError is an error that occurs when a file cannot be found. This can be due to many reasons, such as the file being deleted, moved, or renamed.
It can also occur if the file never existed in the first place.
This error can be very frustrating to deal with, as it can be difficult to determine why the file cannot be found. However, a few things can be checked to try and fix the problem.
First, check the location of the file. If it has been moved, try searching for it in other folders.
If it has been renamed, try using a different name. Finally, if the file does not exist, try creating it.
If you are still unable to find or fix the file, it may be best to contact a professional.
Why Does FileNotFoundError: [WinError 2] The system cannot find the file specified Error Occur in Python
A FileNotFoundError occurs when the file you want to access is missing. This can occur for several reasons:
- The file was deleted by mistake. The user may have inadvertently deleted the file, or the user or another program may have deleted the file.
- The file was renamed to another name.
- The file was moved to another directory. The file was moved to another drive because the error differs from system to system; the causes can differ.
- The path of that file may be wrong in the written command.
How to Fix FileNotFoundError: [WinError 2] The system cannot find the file specified in Python
It is a common error that people encounter when working with computers. It happens when a program tries to access a file or folder it cannot find.
The error messages can be confusing, and there are many reasons that the system cannot find the file specified.
To fix a FileNotFoundError, you need to figure out why Python cannot locate the file. Once you know the cause, you can take steps to fix it, such as making sure the file exists, making sure it’s in the correct directory, or changing the name of the file in your Python program.
Code example:
import subprocess
import os
input = os.path.normcase(r'C:/Users/Vishnu/Desktop/Fortran_Program_Rum/*.txt')
output = os.path.normcase(r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/Output/')
f = open("output", "w")
for i in input:
exe = os.path.normcase(r'~/C:/Program Files (x86)/Silverfrost/ftn95.exe')
fortran_script = os.path.normcase(r'~/C:/Users/Vishnu/Desktop/test_fn/test_f2py.f95')
i = os.path.normcase(i)
subprocess.Popen([exe, fortran_script, "--domain", i])
f.write(i)
Output:
FileNotFoundError: [WinError 2] The system cannot find the file specified
Below are different solutions for Python’s FileNotFoundError: [WinError 2] The system cannot find the file specified.
Change the Order of Slashes
You might see the error if you use slashes incorrectly. To try to fix it, convert the forward slashes / into backward slashes and vice versa, and check if that fixes your error.
Set Up Your Environment
-
First of all, activate your environment. On your device, open the
Anaconda Promptand activate your environment there. -
After that, you can type the following command.
python –m ipykernel install –user -
Now, launch your Jupyter notebook and run the code to check if it works.
Change the Environment Variables
For changing the environment variables, these are the following steps.
- In your PC search bar, search for
Edit the System Environment Variablesand select it from your search results. - In your
System Properties, selectAdvanced, and then select theEnvironment Variablesat the bottom. - Then it shows all properties. Select the property you want to change and click on the
Edit. - If the property is a list of directories or files, then select the
Newbutton and add the variable’s name and value in the new system variable window. - After that, select
OKto apply changes.
Reconfigure the argv Path in Python
A few bunches of users reported that this solution also proved to be effective in their case.
You can solve this type of error by reconfiguring the argv Python path. These are the following steps to resolve this FileNotFoundError.
-
First, open your device and follow the path below.
/python/share/jupyter/kernels/ -
Then, open your
kernel.jsonand set theargvPython path in the following way."argv": [ "C:Anaconda3python.exe", "-m", "ipykernel_launcher", "-f", "{connection_file}" ], "display_name": "Python 3", "language": "python"
- Finally, check whether the error got resolved or not by launching the Jupyter notebook. Now run the code and check the output.
Run Python Using Command Line Interface
-
The error can also occur if the code is not set up in the system path. To work with Sublime, enter the following command to run Python.
C:UsersAdmin>python Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information.After you execute the command, you should see the above message if you’re trying to run Python.
-
But if you receive the following message, it means that Windows cannot run the program because it does not know where the program is located.
C:UsersAdmin>python 'python' is not recognized as an internal or external command, operable program or batch file.
Reconfigure Shell to True Argument
You may get this error if you forget to specify the shell=True argument in the subprocess module’s run method. To fix it, add the shell=True argument to the subprocess module’s run method, or change shell=False to shell=True.
Run the Script as an Administrator
-
To create a shortcut for
python.exe, right-click on the file and selectCreate a Shortcutfrom the drop-down menu. -
Right-click the newly created shortcut and select
Propertiesfrom the drop-down menu. -
In the new pop-up window, change the
Targetfield to something like the below.C:......python.exe yourscript.py -
In the
Shortcuttab, click onAdvancedand check the box forRun as administrator. -
Apply the changes and click
OKto save them.
Disable Anti-Virus
If you’re still having trouble with this error, you may want to check if Windows is blocking access to the folder you’re trying to use. To do this, follow these steps.
- In the search bar near the
Startmenu, search forWindows Securityand select it from the results list. - Select
Virus and Threat Protectionin theWindows Securitypop-up window. - Select
Virus and Threat Protectionsettings. - Turn off Real-Time Protection using the slide button.
- Check if the error is solved.
Conclusion
When you get the FileNotFoundError: [WinError 2] The system cannot find the file specified error message, it means that Windows Explorer has encountered a problem attempting to access the file.
This error can be caused by several different issues with the file system, so you should try troubleshooting the problem before replacing any hardware. This article has listed all possible solutions to this error.