Io unsupportedoperation not writable как исправить

  1. Fix the io.UnsupportedOperation: not writable Error in Python
  2. Conclusion

IO.UnsupportedOperation: Not Writable Error in Python

Python is very efficient in reading and writing data from files. It has a variety of functions to help in file handling.

The basics of file handling involve opening a file using the open() function and reading or writing data based on the file mode.

The open() opens a given file and creates a file object that can be used to perform reading and writing operations on a file.

The file can be opened in different types of modes. By default, it opens the file in read mode.

This tutorial will discuss the io.UnsupportedOperation: not writable error in Python and ways to fix it.

Fix the io.UnsupportedOperation: not writable Error in Python

This error is caused when we try to perform the write operation on a file opened in reading mode. A file opened in read mode can only read the contents.

For example:

with open('sample.txt', 'r') as f:
    f.write('Text')

Output:

io.UnsupportedOperation: not writable

Note that in the above example, we open the file in r mode (read) and try to write some data to this file using the write() function, which causes the error.

Remember to open the file in modes that support this operation to solve this. The write (w) or append (a) modes are used to write some data to a file.

The previous contents are truncated if we open the file in w mode. The a mode adds content to the end of the file and preserves the previous data.

For example:

with open('sample.txt', 'w') as f:
    f.write('Text')

In the above example, we successfully avoid errors and can write data to the file.

If we want to simultaneously read and write data from a file, we can use the r+b mode. We can perform reading and writing operations in binary mode when the file is opened in this mode.

For example:

with open('sample.txt', 'r+b') as f:
    f.write(bytes('Text', 'utf-8'))

Note that we write data as bytes since the file is opened in binary mode. The text is encoded as bytes in the utf-8 encoding in the above example.

Alternatively, we can also use the writable() function to check whether we can perform writing operations using the file handle or not. It returns True or False.

See the code below.

with open('sample.txt', 'r') as f:
    print(f.writable())

with open('sample.txt', 'a') as f:
    print(f.writable())

Output:

The above example shows that the writable function returns False when the file is opened in r mode and returns True when the file is opened in a mode.

Conclusion

To conclude, we discussed the cause behind the io.UnsupportedOperation: not writable error and how to fix it. We discussed how opening the file in the wrong mode can cause this and what file modes support writing operations.

We also demonstrated the use of the writable function that can be used to check whether a file object can perform writing operations or not.

Email validation

#Email validator
import re


def is_email():
    email=input("Enter your email")
    pattern = '[.w]{1,}[@]w+[.]w+'
    file = open('ValidEmails.txt','r')
    if re.match(pattern, email):
        file.write(email)

I am wondering why my data wont write to the disk. Python says that my operation is not supported.

is_email
    file.write(email)
io.UnsupportedOperation: not writable

Nicolas Gervais's user avatar

asked Dec 3, 2014 at 18:13

Lenard 's user avatar

0

You open the variable «file» as a read only then attempt to write to it:

file = open('ValidEmails.txt','r')

Instead, use the ‘w’ flag.

file = open('ValidEmails.txt','w')
...
file.write(email)

Nicolas Gervais's user avatar

answered Dec 3, 2014 at 18:17

triphook's user avatar

triphooktriphook

2,8932 gold badges25 silver badges34 bronze badges

0

file = open('ValidEmails.txt','wb')
file.write(email.encode('utf-8', 'ignore'))

This is solve your encode error also.

answered Aug 30, 2017 at 12:48

Anurag Misra's user avatar

Anurag MisraAnurag Misra

1,50617 silver badges24 bronze badges

use this :

#Email validator
import re


def is_email():
    email=input("Enter your email")
    pattern = '[.w]{1,}[@]w+[.]w+'
    file = open('ValidEmails.txt','w')
    if re.match(pattern, email):
        file.write(email)

answered Apr 5 at 19:44

Avijit Chowdhury's user avatar

Я пишу код python в редакторе NotePad++
вот код:
file = open( ‘D:/test.txt’ )

file.write( ‘Что то’ )

и получаю ошибку:
Traceback (most recent call last):
File «D:p.py», line 3, in
file.write( ‘Что то’ )
io.UnsupportedOperation: not writable

Я в програмировании новичок, подскажите где ошибка


  • Вопрос задан

    более трёх лет назад

  • 11486 просмотров

Попробуйте:
file = open("D:/test.txt","w")
Аргумент «w» нужен для перезаписи файла (весь текст пишется заново), «a» нужен если нужно дописать текст в файле (текст добавляется в конец файла)
PS: Если нужно прочитать файл, то:

file = open("D:/файл.txt","r")
text = file.read()

Надеюсь, я помог вам.

Пригласить эксперта


  • Показать ещё
    Загружается…

27 мая 2023, в 10:30

2000 руб./за проект

27 мая 2023, в 10:26

10000 руб./за проект

27 мая 2023, в 10:16

700 руб./в час

Минуточку внимания

Are you worried 😔 about getting an error “io.unsupportedOperation: not writable” in  Python, and looking for solutions to fix it? Then keep reading this article is just for you.

Python is quite effective when it comes to reading and writing data from files. It provides a wide range of features that makes file handling much easier. Using the open() method to open a file and reading or writing data based on the file mode are the fundamentals of file management.

The open() function opens a specified file and generates a file object that may be used to read and write to files. Various modes can be used to open the file. It opens the file by default in read-only mode.

In this article, we will discuss io.unsupportedOperations: not writeable in Python, what happens when we use these operations in Python, why an error occurs, and how to resolve this error. We will further discuss Python’s io.UnsupportedOperation: not writable error and solutions to it. So without further ado, let’s dive deep into the topic and see some real examples!

Table of Contents
  1. What is Python’s Writable Method?
  2. Why Does the “io.UnsupportedOperation: Not Writable” Error Occur in Python?
  3. What Are The Different Modes of File Handling in Python?
  4. How to Fix The io.UnsupportedOperation: Not Writable Error in Python?

What is Python’s Writable Method?

Python allows us to write strings to files by using the write() method on the text file object and passing the string as an argument. Utilize the open() method to open the text file in write mode. The function returns a file object. Use the file object’s write() method and send it the string as a parameter. Once all writing has been completed, use the close() method to close off the file.

Syntax 

fileobj.writable()

Why Does the “io.UnsupportedOperation: Not Writable” Error Occur in Python?

When you are attempting to write in a file that we do not have permission to write, which indicates that we have opened this file in reading-only mode or possibly without mentioning any mode at all. The solution to this error is to simply append the correct mode, which is ‘w’ mode, which stands for writing mode. As soon as you add “w” mode, the problem will be resolved.

In Python, the IOBase class has a function called writable. If a file stream is capable of writing, this function returns True. False will be returned if the file stream cannot be written to. An exception will be thrown if we use the file object to invoke a write or truncate method that isn’t readable. Let’s see an example:

Code

with open('File.txt', 'r') as f:

    f.write('The Meeting is at 2pm')

Output

IO.UnsupportedOperation Not Writable

In the example above, the file is opened in read-only mode (r mode), and an error occurs when we attempt to write data to the file using the write() method.

What Are The Different Modes of File Handling in Python?

To interact with files in Python there are different modes like to read data we’ve to use r and to write data into the files we’ll use w mode. The following table has all the different available modes that you can use to deal with files in Python.

Access Mode Description
r It opens a file for reading only. In this mode file pointer is placed at the beginning of the file; if we don’t write any access mode, it is our default mode.
rb The rb stands for reading only in binary. It opens a file for reading only in binary format. The file pointer reads from the beginning of the file.
r+ If we write + after r, it opens a file for reading and writing. In this mode, the file pointer is placed at the beginning of the file.
rb+ If we write + after rb, it opens a file for both readings and writing in binary format. In this mode, the file pointer is placed at the beginning of the file.
w If we want to open a file for writing, we have to write w to open a file for writing only. In this mode, a new file is created if the file does not exist. This access mode overwrites the file if the file exists. 
wb Just like rb, we write wb to open a file for writing only in binary format. In this mode, a new file is created if the file does not exist on a given path. This access mode overwrites the file if the file exists.
w+ If we write w+, it will open a file for writing and reading. This mode also overwrites the existing file if the file exists, like w and wb. If the file does not exist on the given path, create a new file for reading and writing.
wb+ Like rb+, writing wb+ mode will open a file for writing and reading in binary format. In this mode, a new file is created if the file does not exist. This access mode overwrites the file if the file exists.
a a stand for appending means writing something at the end of the file. If a file does not exist, it creates a new one.
ab If we write ab as access mode, it will open a file for appending in binary format. 
a+ We write a+ for opening a file for both appending and reading. 
ab+ We write ab+ for opening a file for both appending and reading in binary format. 

This error is caused when we try to perform the write operation on a file opened in reading mode. A file opened in read mode can only read the contents. To fix this, always be sure to open the file in an appropriate mode. 

Following are the ways by which we can write data into a file :

  1. Using write function
  2. Using utf-8 for binary mode
  3. Using append function

Method 1: Using The Write Function

When writing data to a file, the write (w) or append (a) modes are applied.  If you open the file in w mode, the earlier portions are cut off. The file’s previous data is preserved when the data is added to the end of the file in mode. Let’s see an example:

Code

with open('File.txt', 'w') as f:

    f.write('The Meeting is at 2pm)

print("Is this  file writable ?", f.writable())

Output

Is this file writable? True

We can write data in a file when the file is open in writing mode. In the above example, we can write the data “The meeting is at 2 pm”  in File.txt, and to check whether we can write data or not, we can check in True or False.

Method 2: Using utf-8 For Binary Mode

In the below example, we were able to prevent errors and write data to the file. The r+b mode can be used to concurrently read and write data from a file. When the file is opened in this mode, we may carry out reading and writing activities in binary mode.

Code

with open('File.txt', 'r+b') as f:

    f.write(bytes('The Meeting is at 2pm, 'utf-8'))

    print("Is this  file writable ?", f.writable())

Output

Is this file writable? True

Since the file is opened in binary mode, we write data as bytes. In the above example, the text is encoded using the utf-8 encoding as bytes.  To verify whether we can execute writing operations using the file handle or not, we can alternatively utilize the writable() method, returning either true or false.

Method 3: Using The Append Function

We can also use the append function a  to write data into a file named File.txt. Let’s see an example

Code

with open('File.txt', 'r') as f:

    print(f.writable())



with open('File.txt', 'a') as f:

    print(f.writable())

Output

False

True

The above example demonstrates that when a file is opened in r mode, the writable function returns False, and when a file is opened in a mode, it returns True.

Conclusion

To summarize the article, we have discussed what causes the io.UnsupportedOperation: not writable error in Python. How to resolve the io.UnsupportedOperation: not writable error. Furthermore, we discussed what file modes permit writing activities as well as how opening the file in the incorrect mode might lead to this.

The best way is to use the write function, but you have to make sure the file is open in write mode w  and not in read mode r,  as that will generate an UnsupportedOperation: not writable error.  You can also use the writable function to check whether the file is writable or not. This will print true if the file is editable or writable. If the file is not writable, it will return a false.

We’ve also talked about how to utilize the writable function, which can be used to determine whether or not a file object is capable of performing writing operations.

Let’s have a quick recap of the topics discussed in this article.

  1. What is the Python writable method?
  2. Why does io.unsupportedOperation: not writable error occur?
  3. How to fix the io.unsupportedOperation: not writable error in python?
  4. Using the write function.
  5. Using utf-8 for binary mode.
  6. Using the append function.

If you’ve found this article helpful, comment below and let 👇 know which solutions have helped you solve the problem.

Welcome

Hi! If you want to learn how to work with files in Python, then this article is for you. Working with files is an important skill that every Python developer should learn, so let’s get started.

In this article, you will learn:

  • How to open a file.
  • How to read a file.
  • How to create a file.
  • How to modify a file.
  • How to close a file.
  • How to open files for multiple operations.
  • How to work with file object methods.
  • How to delete files.
  • How to work with context managers and why they are useful.
  • How to handle exceptions that could be raised when you work with files.
  • and more!

Let’s begin! ✨

🔹 Working with Files: Basic Syntax

One of the most important functions that you will need to use as you work with files in Python is open(), a built-in function that opens a file and allows your program to use it and work with it.

This is the basic syntax:

image-48

💡 Tip: These are the two most commonly used arguments to call this function. There are six additional optional arguments. To learn more about them, please read this article in the documentation.

First Parameter: File

The first parameter of the open() function is file, the absolute or relative path to the file that you are trying to work with.

We usually use a relative path, which indicates where the file is located relative to the location of the script (Python file) that is calling the open() function.

For example, the path in this function call:

open("names.txt") # The relative path is "names.txt"

Only contains the name of the file. This can be used when the file that you are trying to open is in the same directory or folder as the Python script, like this:

image-7

But if the file is within a nested folder, like this:

image-9

The names.txt file is in the «data» folder

Then we need to use a specific path to tell the function that the file is within another folder.

In this example, this would be the path:

open("data/names.txt")

Notice that we are writing data/ first (the name of the folder followed by a /) and then names.txt (the name of the file with the extension).

💡 Tip: The three letters .txt that follow the dot in names.txt is the «extension» of the file, or its type. In this case, .txt indicates that it’s a text file.

Second Parameter: Mode

The second parameter of the open() function is the mode, a string with one character. That single character basically tells Python what you are planning to do with the file in your program.

Modes available are:

  • Read ("r").
  • Append ("a")
  • Write ("w")
  • Create ("x")

You can also choose to open the file in:

  • Text mode ("t")
  • Binary mode ("b")

To use text or binary mode, you would need to add these characters to the main mode. For example: "wb" means writing in binary mode.

💡 Tip: The default modes are read ("r") and text ("t"), which means «open for reading text» ("rt"), so you don’t need to specify them in open() if you want to use them because they are assigned by default. You can simply write open(<file>).

Why Modes?

It really makes sense for Python to grant only certain permissions based what you are planning to do with the file, right? Why should Python allow your program to do more than necessary? This is basically why modes exist.

Think about it — allowing a program to do more than necessary can problematic. For example, if you only need to read the content of a file, it can be dangerous to allow your program to modify it unexpectedly, which could potentially introduce bugs.

🔸 How to Read a File

Now that you know more about the arguments that the open() function takes, let’s see how you can open a file and store it in a variable to use it in your program.

This is the basic syntax:

image-41

We are simply assigning the value returned to a variable. For example:

names_file = open("data/names.txt", "r")

I know you might be asking: what type of value is returned by open()?

Well, a file object.

Let’s talk a little bit about them.

File Objects

According to the Python Documentation, a file object is:

An object exposing a file-oriented API (with methods such as read() or write()) to an underlying resource.

This is basically telling us that a file object is an object that lets us work and interact with existing files in our Python program.

File objects have attributes, such as:

  • name: the name of the file.
  • closed: True if the file is closed. False otherwise.
  • mode: the mode used to open the file.

image-57

For example:

f = open("data/names.txt", "a")
print(f.mode) # Output: "a"

Now let’s see how you can access the content of a file through a file object.

Methods to Read a File

For us to be able to work file objects, we need to have a way to «interact» with them in our program and that is exactly what methods do. Let’s see some of them.

Read()

The first method that you need to learn about is read(), which returns the entire content of the file as a string.

image-11

Here we have an example:

f = open("data/names.txt")
print(f.read())

The output is:

Nora
Gino
Timmy
William

You can use the type() function to confirm that the value returned by f.read() is a string:

print(type(f.read()))

# Output
<class 'str'>

Yes, it’s a string!

In this case, the entire file was printed because we did not specify a maximum number of bytes, but we can do this as well.

Here we have an example:

f = open("data/names.txt")
print(f.read(3))

The value returned is limited to this number of bytes:

Nor

❗️Important: You need to close a file after the task has been completed to free the resources associated to the file. To do this, you need to call the close() method, like this:

image-22

Readline() vs. Readlines()

You can read a file line by line with these two methods. They are slightly different, so let’s see them in detail.

readline() reads one line of the file until it reaches the end of that line. A trailing newline character (n) is kept in the string.

💡 Tip: Optionally, you can pass the size, the maximum number of characters that you want to include in the resulting string.

image-19

For example:

f = open("data/names.txt")
print(f.readline())
f.close()

The output is:

Nora

This is the first line of the file.

In contrast, readlines() returns a list with all the lines of the file as individual elements (strings). This is the syntax:

image-21

For example:

f = open("data/names.txt")
print(f.readlines())
f.close()

The output is:

['Noran', 'Ginon', 'Timmyn', 'William']

Notice that there is a n (newline character) at the end of each string, except the last one.

💡 Tip: You can get the same list with list(f).

You can work with this list in your program by assigning it to a variable or using it in a loop:

f = open("data/names.txt")

for line in f.readlines():
    # Do something with each line
    
f.close()

We can also iterate over f directly (the file object) in a loop:

f = open("data/names.txt", "r")

for line in f:
	# Do something with each line

f.close()

Those are the main methods used to read file objects. Now let’s see how you can create files.

🔹 How to Create a File

If you need to create a file «dynamically» using Python, you can do it with the "x" mode.

Let’s see how. This is the basic syntax:

image-58

Here’s an example. This is my current working directory:

image-29

If I run this line of code:

f = open("new_file.txt", "x")

A new file with that name is created:

image-30

With this mode, you can create a file and then write to it dynamically using methods that you will learn in just a few moments.

💡 Tip: The file will be initially empty until you modify it.

A curious thing is that if you try to run this line again and a file with that name already exists, you will see this error:

Traceback (most recent call last):
  File "<path>", line 8, in <module>
    f = open("new_file.txt", "x")
FileExistsError: [Errno 17] File exists: 'new_file.txt'

According to the Python Documentation, this exception (runtime error) is:

Raised when trying to create a file or directory which already exists.

Now that you know how to create a file, let’s see how you can modify it.

🔸 How to Modify a File

To modify (write to) a file, you need to use the write() method. You have two ways to do it (append or write) based on the mode that you choose to open it with. Let’s see them in detail.

Append

«Appending» means adding something to the end of another thing. The "a" mode allows you to open a file to append some content to it.

For example, if we have this file:

image-43

And we want to add a new line to it, we can open it using the "a" mode (append) and then, call the write() method, passing the content that we want to append as argument.

This is the basic syntax to call the write() method:

image-52

Here’s an example:

f = open("data/names.txt", "a")
f.write("nNew Line")
f.close()

💡 Tip: Notice that I’m adding n before the line to indicate that I want the new line to appear as a separate line, not as a continuation of the existing line.

This is the file now, after running the script:

image-45

💡 Tip: The new line might not be displayed in the file until f.close() runs.

Write

Sometimes, you may want to delete the content of a file and replace it entirely with new content. You can do this with the write() method if you open the file with the "w" mode.

Here we have this text file:

image-43

If I run this script:

f = open("data/names.txt", "w")
f.write("New Content")
f.close()

This is the result:

image-46

As you can see, opening a file with the "w" mode and then writing to it replaces the existing content.

💡 Tip: The write() method returns the number of characters written.

If you want to write several lines at once, you can use the writelines() method, which takes a list of strings. Each string represents a line to be added to the file.

Here’s an example. This is the initial file:

image-43

If we run this script:

f = open("data/names.txt", "a")
f.writelines(["nline1", "nline2", "nline3"])
f.close()

The lines are added to the end of the file:

image-47

Open File For Multiple Operations

Now you know how to create, read, and write to a file, but what if you want to do more than one thing in the same program? Let’s see what happens if we try to do this with the modes that you have learned so far:

If you open a file in "r" mode (read), and then try to write to it:

f = open("data/names.txt")
f.write("New Content") # Trying to write
f.close()

You will get this error:

Traceback (most recent call last):
  File "<path>", line 9, in <module>
    f.write("New Content")
io.UnsupportedOperation: not writable

Similarly, if you open a file in "w" mode (write), and then try to read it:

f = open("data/names.txt", "w")
print(f.readlines()) # Trying to read
f.write("New Content")
f.close()

You will see this error:

Traceback (most recent call last):
  File "<path>", line 14, in <module>
    print(f.readlines())
io.UnsupportedOperation: not readable

The same will occur with the "a" (append) mode.

How can we solve this? To be able to read a file and perform another operation in the same program, you need to add the "+" symbol to the mode, like this:

f = open("data/names.txt", "w+") # Read + Write
f = open("data/names.txt", "a+") # Read + Append
f = open("data/names.txt", "r+") # Read + Write

Very useful, right? This is probably what you will use in your programs, but be sure to include only the modes that you need to avoid potential bugs.

Sometimes files are no longer needed. Let’s see how you can delete files using Python.

🔹 How to Delete Files

To remove a file using Python, you need to import a module called os which contains functions that interact with your operating system.

💡 Tip: A module is a Python file with related variables, functions, and classes.

Particularly, you need the remove() function. This function takes the path to the file as argument and deletes the file automatically.

image-56

Let’s see an example. We want to remove the file called sample_file.txt.

image-34

To do it, we write this code:

import os
os.remove("sample_file.txt")
  • The first line: import os is called an «import statement». This statement is written at the top of your file and it gives you access to the functions defined in the os module.
  • The second line: os.remove("sample_file.txt") removes the file specified.

💡 Tip: you can use an absolute or a relative path.

Now that you know how to delete files, let’s see an interesting tool… Context Managers!

🔸 Meet Context Managers

Context Managers are Python constructs that will make your life much easier. By using them, you don’t need to remember to close a file at the end of your program and you have access to the file in the particular part of the program that you choose.

Syntax

This is an example of a context manager used to work with files:

image-33

💡 Tip: The body of the context manager has to be indented, just like we indent loops, functions, and classes. If the code is not indented, it will not be considered part of the context manager.

When the body of the context manager has been completed, the file closes automatically.

with open("<path>", "<mode>") as <var>:
    # Working with the file...

# The file is closed here!

Example

Here’s an example:

with open("data/names.txt", "r+") as f:
    print(f.readlines()) 

This context manager opens the names.txt file for read/write operations and assigns that file object to the variable f. This variable is used in the body of the context manager to refer to the file object.

Trying to Read it Again

After the body has been completed, the file is automatically closed, so it can’t be read without opening it again. But wait! We have a line that tries to read it again, right here below:

with open("data/names.txt", "r+") as f:
    print(f.readlines())

print(f.readlines()) # Trying to read the file again, outside of the context manager

Let’s see what happens:

Traceback (most recent call last):
  File "<path>", line 21, in <module>
    print(f.readlines())
ValueError: I/O operation on closed file.

This error is thrown because we are trying to read a closed file. Awesome, right? The context manager does all the heavy work for us, it is readable, and concise.

🔹 How to Handle Exceptions When Working With Files

When you’re working with files, errors can occur. Sometimes you may not have the necessary permissions to modify or access a file, or a file might not even exist.

As a programmer, you need to foresee these circumstances and handle them in your program to avoid sudden crashes that could definitely affect the user experience.

Let’s see some of the most common exceptions (runtime errors) that you might find when you work with files:

FileNotFoundError

According to the Python Documentation, this exception is:

Raised when a file or directory is requested but doesn’t exist.

For example, if the file that you’re trying to open doesn’t exist in your current working directory:

f = open("names.txt")

You will see this error:

Traceback (most recent call last):
  File "<path>", line 8, in <module>
    f = open("names.txt")
FileNotFoundError: [Errno 2] No such file or directory: 'names.txt'

Let’s break this error down this line by line:

  • File "<path>", line 8, in <module>. This line tells you that the error was raised when the code on the file located in <path> was running. Specifically, when line 8 was executed in <module>.
  • f = open("names.txt"). This is the line that caused the error.
  • FileNotFoundError: [Errno 2] No such file or directory: 'names.txt' . This line says that a FileNotFoundError exception was raised because the file or directory names.txt doesn’t exist.

💡 Tip: Python is very descriptive with the error messages, right? This is a huge advantage during the process of debugging.

PermissionError

This is another common exception when working with files. According to the Python Documentation, this exception is:

Raised when trying to run an operation without the adequate access rights — for example filesystem permissions.

This exception is raised when you are trying to read or modify a file that don’t have permission to access. If you try to do so, you will see this error:

Traceback (most recent call last):
  File "<path>", line 8, in <module>
    f = open("<file_path>")
PermissionError: [Errno 13] Permission denied: 'data'

IsADirectoryError

According to the Python Documentation, this exception is:

Raised when a file operation is requested on a directory.

This particular exception is raised when you try to open or work on a directory instead of a file, so be really careful with the path that you pass as argument.

How to Handle Exceptions

To handle these exceptions, you can use a try/except statement. With this statement, you can «tell» your program what to do in case something unexpected happens.

This is the basic syntax:

try:
	# Try to run this code
except <type_of_exception>:
	# If an exception of this type is raised, stop the process and jump to this block
    

Here you can see an example with FileNotFoundError:

try:
    f = open("names.txt")
except FileNotFoundError:
    print("The file doesn't exist")

This basically says:

  • Try to open the file names.txt.
  • If a FileNotFoundError is thrown, don’t crash! Simply print a descriptive statement for the user.

💡 Tip: You can choose how to handle the situation by writing the appropriate code in the except block. Perhaps you could create a new file if it doesn’t exist already.

To close the file automatically after the task (regardless of whether an exception was raised or not in the try block) you can add the finally block.

try:
	# Try to run this code
except <exception>:
	# If this exception is raised, stop the process immediately and jump to this block
finally: 
	# Do this after running the code, even if an exception was raised

This is an example:

try:
    f = open("names.txt")
except FileNotFoundError:
    print("The file doesn't exist")
finally:
    f.close()

There are many ways to customize the try/except/finally statement and you can even add an else block to run a block of code only if no exceptions were raised in the try block.

💡 Tip: To learn more about exception handling in Python, you may like to read my article: «How to Handle Exceptions in Python: A Detailed Visual Introduction».

🔸 In Summary

  • You can create, read, write, and delete files using Python.
  • File objects have their own set of methods that you can use to work with them in your program.
  • Context Managers help you work with files and manage them by closing them automatically when a task has been completed.
  • Exception handling is key in Python. Common exceptions when you are working with files include FileNotFoundError, PermissionError and IsADirectoryError. They can be handled using try/except/else/finally.

I really hope you liked my article and found it helpful. Now you can work with files in your Python projects. Check out my online courses. Follow me on Twitter. ⭐️

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Понравилась статья? Поделить с друзьями:
  • Как найти бронежилет бесу
  • Как составить порядок составления
  • Как найти общий коэффициент миграции
  • Как исправить маленькие ногти на ногах
  • Как составить кроссворд на тему 1812 года