Ошибка файл не найден python

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's user avatar

mkrieger1

19.3k5 gold badges54 silver badges65 bronze badges

asked Jul 15, 2013 at 16:13

Ashley Elisabeth Stallings's user avatar

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's user avatar

wjandrea

28.5k9 gold badges62 silver badges82 bronze badges

answered Jul 15, 2013 at 16:17

Dr. Jan-Philip Gehrcke's user avatar

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

adhaamehab's user avatar

answered Jul 15, 2013 at 16:18

Jon Kiparsky's user avatar

Jon KiparskyJon Kiparsky

7,5192 gold badges23 silver badges38 bronze badges

0

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

Spookpadda's user avatar

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's user avatar

wjandrea

28.5k9 gold badges62 silver badges82 bronze badges

answered Jul 15, 2013 at 16:27

user1555863's user avatar

user1555863user1555863

2,5676 gold badges35 silver badges50 bronze badges

1

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

RandML000's user avatar

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 Kiparsky's user avatar

Jon KiparskyJon Kiparsky

7,5192 gold badges23 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:\Users\soman\Desktop\test.txt','r') as f: data=f.readlines() for i in data: print(i)

answered Nov 3, 2021 at 7:08

SOMANATH OJHA's user avatar

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:\Users\noob\Desktop\Python\Course 2\python.txt.txt

That is why it was giving a error.

Name your file without .txt it will run.

Jamiu S.'s user avatar

Jamiu S.

5,2395 gold badges12 silver badges36 bronze badges

answered Aug 14, 2020 at 16:37

noob's user avatar

In Python, there are two types of errors: syntax errors and exceptions. Syntax errors, also known as parsing errors, occur when Python’s parser encounters a syntax error. Exceptions, on the other hand, occur when syntactically correct Python code results in an error. The «File Not Found Error» in Python is an example of an exception.

The «File Not Found Error» (FileNotFoundError) is raised when Python code attempts to open a file that doesn’t exist, cannot be found at the specified location, or is not a regular file but a different kind of file system object. This can happen for several reasons:

  • The file doesn’t exist
  • The file is in a different directory than specified
  • The program has insufficient permissions to access the file
  • The ‘file’ is a symbolic link that points to a non-existent file
  • The ‘file’ is actually a directory, named pipe, or other non-regular file type

When a «File Not Found Error» occurs, it interrupts the execution of the program. However, it can be handled through Python’s error handling mechanism (using «try» and «except» statements), preventing the program from crashing and providing an opportunity to handle the situation gracefully. This includes handling situations where the file you’re trying to open is not a regular file but a symbolic link, directory, or another type of file system object.

Different reasons for getting ‘File Not Found Error’

1. Incorrect File Path:

One of the most common causes of the ‘File Not Found Error’ is providing an incorrect file path. This could be due to a simple typo in the file name or directory, or using the wrong case in case-sensitive file systems.

# Incorrect file name
with open('wrong_name.txt', 'r') as f:
    content = f.read()

ALSO READ: Master Python Multiprocessing [In-Depth Tutorial]

2. File Does Not Exist:

Another straightforward cause is trying to access a file that does not exist in the file system. This could occur due to deleting a file manually while the Python program is still running or an error in the program that causes a file to be deleted prematurely.

# Nonexistent file
with open('nonexistent_file.txt', 'r') as f:
    content = f.read()

3. Improper Use of Relative and Absolute Paths:

Errors often arise from confusion between relative and absolute file paths. Relative file paths are interpreted in relation to the current working directory, which might not be the same as the directory where the Python script is located. On the other hand, an absolute path is a full path to the location of a file, starting from the root directory.

# Incorrect relative path
with open('wrong_directory/my_file.txt', 'r') as f:
    content = f.read()

# Incorrect absolute path
with open('/wrong_directory/my_file.txt', 'r') as f:
    content = f.read()

4. Trying to Open a Non-regular File:

As mentioned previously, trying to open a file that is not a regular file can also cause a ‘File Not Found Error’. This includes symbolic links pointing to non-existent files, directories, named pipes, and more.

# Trying to open a symbolic link pointing to a nonexistent file
with open('symbolic_link_to_nonexistent_file', 'r') as f:
    content = f.read()

5. Insufficient File Permissions:

If your program doesn’t have the necessary permissions to access a file, it can also result in a ‘File Not Found Error’. This is common in multi-user systems where file access permissions are strictly managed.

# File without necessary permissions
with open('restricted_file.txt', 'r') as f:
    content = f.read()

How to Handle ‘File Not Found Error’

In Python, error handling is performed using the try-except statement. Here’s a basic structure:

try:
    # code block where an exception might occur
except ExceptionType:
    # code to be executed in case the exception occurs

You put the code that might throw an exception in the try block and the code to handle the exception in the except block. Python allows multiple except blocks to handle different types of exceptions separately. If an exception occurs in the try block, Python will stop executing further code in the try block and jump to the except block that handles that exception type.

ALSO READ: How to find length of Set in Python? [SOLVED]

When working with files, a common error to handle is the ‘FileNotFoundError‘. Here’s how to handle it:

try:
    with open('non_existent_file.txt', 'r') as f:
        print(f.read())
except FileNotFoundError:
    print('The file could not be found.')

In this example, if the file does not exist, Python will throw a FileNotFoundError. The except block catches this exception and prints a message saying ‘The file could not be found.’ instead of stopping the program.

It’s good practice to handle exceptions at the point where you have the information to deal with them appropriately. For example, if a function is responsible for reading a file and processing its contents, that function should handle any file-related exceptions because it knows what files it’s dealing with and what errors might arise.

In some cases, you may want to do something when an exception occurs and then re-raise the exception. You can do this with the ‘raise’ statement:

try:
    with open('non_existent_file.txt', 'r') as f:
        print(f.read())
except FileNotFoundError:
    print('The file could not be found.')
    raise

Here, if the file doesn’t exist, Python will print a message and then re-raise the FileNotFoundError, allowing it to be caught and handled at a higher level in your code.

Best Practices to Avoid ‘File Not Found Error’

1. Check If File Exists Before Opening It:

We can use the os.path module to check if the file exists before trying to open it can prevent a ‘File Not Found Error. Here’s an example:

import os

file_path = 'my_file.txt'
if os.path.isfile(file_path):
    with open(file_path, 'r') as f:
        print(f.read())
else:
    print('The file does not exist.')

In this code, os.path.isfile(file_path) returns True if the file exists and False otherwise.

2. Use Absolute Paths Instead of Relative Paths:

While it’s not always possible, using absolute paths can prevent errors due to confusion about the current working directory. If you need to use relative paths, make sure you know what the current working directory is. You can use os.getcwd() to check the current working directory.

ALSO READ: Python struct module Explained [Easy Examples]

A relative path is a path that starts from the current working directory. For instance, if the current working directory is /home/user/documents, and there’s a file named my_file.txt within this directory, you can open this file with the relative path like this:

with open('my_file.txt', 'r') as f:
    print(f.read())

An absolute path is a path that starts from the root directory. It is a complete path to the location of a file or a directory in a file system. The absolute path to the file in the previous example would be /home/user/documents/my_file.txt. You can open the file with the absolute path like this:

with open('/home/user/documents/my_file.txt', 'r') as f:
    print(f.read())

3. Handle File Paths Carefully:

File paths can be a source of errors, especially on systems where the path separator varies (like / on Unix-based systems and \ on Windows). You can use os.path.join() to create file paths in a platform-independent way:

import os

file_path = os.path.join('my_directory', 'my_file.txt')

4. Ensure Proper File Permissions:

If your program needs to read or write files, make sure it has the necessary permissions to do so. This might mean running the program with a different user or modifying the file permissions.

In order to read, write, or execute a file in Python, the program must have the necessary file permissions. If the program lacks the permissions to perform the requested operation, Python will raise a PermissionError.

You can handle this exception in a tryexcept block. Here’s an example:

try:
    with open('restricted_file.txt', 'w') as f:
        f.write('Hello, World!')
except PermissionError:
    print('Permission denied. Please check if you have the correct permissions to write to this file.')

In this example, Python tries to open a file named ‘restricted_file.txt’ in write mode and write ‘Hello, World!’ to it. If the program doesn’t have the necessary permissions to perform this operation, it will raise a PermissionError, and the except block will catch this exception and print a message to inform the user.

ALSO READ: Python super() function explained [Easy Examples]

5. Check File Type Before Accessing:

Python’s os module provides the os.path module which can be used to perform such checks. Here’s a simple example:

import os

file_path = 'my_file.txt'

if os.path.isfile(file_path):
    print('Regular file')
    with open(file_path, 'r') as f:
        print(f.read())
elif os.path.isdir(file_path):
    print('Directory')
    # perform directory operations here
elif os.path.islink(file_path):
    print('Symbolic link')
    # perform symbolic link operations here
else:
    print('Unknown file type')
    # handle other file types here

In this code:

  • os.path.isfile(file_path) checks if the path is a regular file.
  • os.path.isdir(file_path) checks if the path is a directory.
  • os.path.islink(file_path) checks if the path is a symbolic link.

Each of these functions returns True if the path is of the corresponding type, and False otherwise. You can use these checks to determine the file type and handle each type accordingly.

Summary

In this article, we explored Python’s ‘File Not Found Error’, an exception raised when the Python interpreter can’t find a file that the code is attempting to open or manipulate. This error can occur due to a variety of reasons: the file doesn’t exist, the file is in a different location, the file is not a regular file (like a symbolic link, directory, or other non-regular file types), or the program doesn’t have the necessary permissions to access the file.

We also examined the concept of exception handling in Python, specifically focusing on how the ‘File Not Found Error’ can be gracefully handled using try-except blocks. This method allows the program to continue running even when such an error occurs, enhancing the robustness of the Python code.

Several scenarios were discussed with code snippets to illustrate instances where the ‘File Not Found Error’ may be encountered. In particular, these scenarios highlighted the differences between absolute and relative file paths and the implications of incorrect file paths or non-existent directories.

Finally, we discussed a variety of tips and tricks to avoid encountering the ‘File Not Found Error’. These include checking if a file exists before trying to open it using the os.path module, using absolute paths instead of relative paths when possible, careful handling of file paths, ensuring proper file permissions, and handling errors in a graceful manner.

ALSO READ: How to get file size in Python? [SOLVED]

Key Takeaways

  1. ‘File Not Found Error’ in Python is a common exception that can be avoided and handled with the right approaches.
  2. Using exception handling (try-except blocks), we can catch and manage these exceptions effectively to prevent the program from crashing.
  3. Checking the file or directory’s existence and type before trying to open it can help avoid this error.
  4. Ensuring correct use of absolute and relative paths and verifying proper file permissions are crucial steps.
  5. Even with precautions, errors can still occur. It’s essential to code in a way that gracefully handles potential exceptions and minimizes their impact.
  6. Understanding the nature of ‘File Not Found Error’ and the strategies to handle it will lead to the development of more robust and reliable Python programs.

Если вы получили сообщение об ошибке «FileNotFoundError: [WinError 2] Система не может найти указанный файл», это означает, что по указанному вами пути нет файла.

В этом руководстве мы узнаем, когда это вызывается программой, и как обрабатывать ошибку FileNotFoundError в Python.

Воссоздание ошибки

Давайте воссоздадим этот скрипт, где интерпретатор Python выдает FileNotFoundError.

В следующей программе мы пытаемся удалить файл, но мы предоставили путь, которого не существует. Python понимает эту ситуацию, как отсутствие файла.

import os

os.remove('C:\workspace\python\data.txt')
print('The file is removed.')

В приведенной выше программе мы попытались удалить файл, находящийся по пути C:\workspace\python\data.txt.

Консольный вывод:

C:\workspace\python>dir data*
 Volume in drive C is OS
 Volume Serial Number is B24

 Directory of C:\workspace\python

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

Разрабатывая приложения вам придется работать с файлами, анализировать большие объемы данных, сохранять пользовательские данные, чтобы они не терялись по завершению работы программы. Также при работе с файлами важно научиться обрабатывать ошибки, чтобы они не привели к аварийному завершению программы. Для этого в 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(«Язык программирования Python\n«)
    file.write(«Язык программирования Java\n«)
    file.write(«Язык программирования Perl\n«)

Результат будет выглядеть так:

Язык программирования Python
Язык программирования Java
Язык программирования Perl

2.3. Присоединение данных к файлу на Python 

Для добавления новых данных в файл, вместо того чтобы постоянно перезаписывать файл, откройте файл в режиме присоединения ‘ a ‘. Все новые строки добавятся в конец файла. Возьмем созданный файл из раздела 2.2 ‘memory.txt’. Добавим в него еще пару строк.

filename = ‘memory.txt’

with open(filename, ‘a’) as file:
    file.write(«Hello world\n»)
    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

In this article, we will be addressing a very common error – filenotfounderror – in Python . If you have worked with Python before, you would have faced this situation too, where you write all your code, maintain proper indents in it, put comments line, double-check for mistypes, and after making sure that everything is right and in its place, you run the code and end up getting ‘filenotfounderror’ in the compiler line.

Frustrating, isn’t it? Don’t worry, we will make sure to cover all possible ways to resolve this problem so that you do not encounter it ever again.

Also read: Handling IOErrors in Python – A Complete Guide

What is filenotfounderror

It is a system message that the compiler throws when you are trying to execute a command that requires a file that the system cannot find. It can be for various reasons like – wrong file path specified, the file is present in another directory, or an extension error. We will address the points in this article. But let’s first recreate the problem in our system.

We will be writing a program to load a .csv file into a pandas data frame and then print that data frame.

import pandas as pd

df=pd.read_csv("nifty 2020 crash")
print(df)

Filenotfounderror_image.png
Filenotfounderror

How to Fix the Python filenotfounderror?

When you run your python code in the terminal, it searches for the file in the root directory from where the terminal is running. A common misconception people have is that when you run a python code to read a file, the terminal searches that file in the whole computer, which is incorrect.

All your files that are needed for your program should be present in the root directory from where the terminal is activated.

This problem can be resolved in two ways:

Method 1: Specifying the complete file path

When we run our program, we state the file name in the program. The compiler searches for it in the root directory and throws errors. The solution to this problem is specifying the whole file path in the code.

import pandas as pd

df = pd.read_csv(r"C:\Users\Win 10\Desktop\python_errorsolving\nifty 2020 crash.csv")
print(df)
solving_filenotfound_method-1.png

Note: Observe, while specifying the file path, we added an r before writing the path, pd.read_csv(r"C:\.......). It is used to convert simple strings to raw strings. If we do not add r before specifying our file path, the system is gonna treat that line of code as a normal string input instead of a file path.

Method 2: Using a .txt file to run Python script

In this method, we use a very simple but effective approach to this problem. We write our code in a .txt file and store it in the directory where the file we require is present. When we run this .txt file with python, the compiler searches for that file only in that directory. This method does not require us to specify the whole file path but we need to make sure that the terminal has been run from the right directory.

To illustrate this example, we have created a directory in our desktop named, ‘python_errorsolving’. This directory contains two files, – the .txt file containing python codes and the .csv file we needed for our code.

method2_notepad_screenshot.png

To run this file from the terminal, go to the directory manually using cd, and then run this file with syntax python error_crt.txt or whatever your file name is.

method2_dos_screenshot.png

As you can see, this method does not require us to specify the whole file path. It is useful when you have to work with multiple files because specifying the whole path for each specific file can be a tedious job.

Method 3: Workaround for filenotfounderror

This is not a solution but rather a workaround for this problem. Suppose you are in a certain situation where the file path is the same but you have to load consecutive different files. In that case, you can store your filename and file path in two different variables and then concatenate them in a third variable. This way you can make combinations of multiple different files, and then load them easily.

To illustrate this solution, we will create a .txt file, with the codes:

import pandas as pd

filename = "nifty 2020 crash.csv"
filepath = "C:\\Users\\Win 10\\Desktop\\python_errorsolving\\"
file = filepath+filename

df = pd.read_csv(file)
print(df)

alterate_method_dos-screenshot.png

Using an IDE to fix the filenotfounderror

Integrated development environments or IDE’s are a great way to manage our files and environment variables. This helps to create virtual environments for your codes so that the needed libraries and environment variables do not interact with our other projects. In this section, we will create a project in PyCharm IDE, and see how easily we can store and interact with our files.

To demonstrate this example, we have created a .csv file containing school records, and it is named ‘book1.csv’. To import it in PyCharm, follow these steps:

Step 1: Go to File>new project…>give a file name>create.

Step 2: Copy your .csv file and paste it into that project.

method_ide_paste_screen-shot.png

Once you paste the file, you can directly access that file with your codes, without having to specify the whole path. You can simply work with the filename.

import pandas as pd

df = pd.read_csv('Book1.csv', sep='|')
print(df)

Result:

method_ide_paste_screen-shot2.png

Conclusion

In this article, we have observed the different cases where the system cannot locate your files. We also looked at the different solutions that are possible to these problems, from manually specifying paths, to using IDE’s for a better outcome. I hope this article solved your problem

Понравилась статья? Поделить с друзьями:
  • Ошибка файл не найден номер
  • Ошибка файл не найден латех
  • Ошибка файл не должен быть исполняемым вконтакте
  • Ошибка файл настроек поврежден или недействителен
  • Ошибка файл или папка повреждены чтение невозможно торрент