The Following Files Could Not Be Imported Because They Could Not Be Read

Python Write to File – Open, Read, Append, and Other File Handling Functions Explained

Welcome

Hi! If y'all want to learn how to work with files in Python, then this article is for you. Working with files is an of import skill that every Python developer should learn, so allow's go started.

In this commodity, 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 shut 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 than!

Allow's begin! ✨

🔹 Working with Files: Basic Syntax

1 of the most important functions that you will need to use equally yous work with files in Python is open up() , a built-in part that opens a file and allows your program to use it and work with information technology.

This is the basic syntax:

image-48

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

Starting time Parameter: File

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

Nosotros usually apply a relative path, which indicates where the file is located relative to the location of the script (Python file) that is calling the open up() 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

Merely if the file is inside a nested folder, like this:

image-9
The names.txt file is in the "information" folder

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

In this example, this would be the path:

                open("information/names.txt")              

Notice that we are writing data/ first (the name of the folder followed past 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 example, .txt indicates that it'south a text file.

2nd Parameter: Mode

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

Modes available are:

  • Read ("r").
  • Append ("a")
  • Write ("due west")
  • Create ("10")

You tin also cull to open the file in:

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

To use text or binary style, you lot 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 up for reading text" ("rt"), so you lot don't need to specify them in open up() if you lot want to utilise them because they are assigned by default. You lot can simply write open(<file>).

Why Modes?

Information technology really makes sense for Python to grant only sure permissions based what yous 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.

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

🔸 How to Read a File

Now that you know more nigh the arguments that the open() part takes, let'south meet how you can open up a file and store it in a variable to apply it in your program.

This is the bones syntax:

image-41

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

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

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

Well, a file object.

Let's talk a little flake about them.

File Objects

Co-ordinate 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 resources.

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

File objects accept attributes, such every bit:

  • name: the name of the file.
  • airtight: Truthful if the file is closed. Imitation otherwise.
  • mode: the mode used to open the file.
image-57

For example:

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

At present let's see how you can admission the content of a file through a file object.

Methods to Read a File

For us to be able to piece of work file objects, nosotros need to have a way to "interact" with them in our program and that is exactly what methods do. Let'due south see some of them.

Read()

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

image-11

Here we take an example:

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

The output is:

                Nora Gino Timmy William              

Y'all tin use the type() function to confirm that the value returned by f.read() is a string:

                print(type(f.read()))  # Output <form 'str'>              

Yes, information technology's a string!

In this example, 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 lot demand to close a file afterward the task has been completed to free the resources associated to the file. To do this, you need to call the close() method, similar this:

image-22

Readline() vs. Readlines()

You tin read a file line past line with these two methods. They are slightly different, and then let's see them in detail.

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

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

image-19

For example:

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

The output is:

                Nora                              

This is the starting time 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:

                ['Nora\north', 'Gino\n', 'Timmy\n', 'William']              

Find that there is a \n (newline graphic symbol) at the end of each string, except the last one.

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

You tin piece of work with this list in your program by assigning information technology to a variable or using it in a loop:

                f = open("information/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("information/names.txt", "r")  for line in f: 	# Practice 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 tin can do it with the "10" manner.

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 lawmaking:

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

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 lot volition acquire in merely a few moments.

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

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

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

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

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

Now that you know how to create a file, allow's see how you tin can modify information technology.

🔸 How to Modify a File

To modify (write to) a file, you demand to use the write() method. Yous have two ways to do it (append or write) based on the mode that y'all cull to open it with. Let's see them in detail.

Append

"Appending" means adding something to the end of some other matter. The "a" manner allows you to open a file to append some content to it.

For example, if nosotros take this file:

image-43

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

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

image-52

Hither'southward an example:

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

💡 Tip: Find that I'm adding \n earlier the line to bespeak that I want the new line to appear as a split up line, not every bit a continuation of the existing line.

This is the file at present, 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 desire to delete the content of a file and replace it entirely with new content. Y'all tin can do this with the write() method if you open the file with the "westward" mode.

Here we have this text file:

image-43

If I run this script:

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

This is the result:

image-46

As you lot can run across, 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 yous desire to write several lines at once, y'all 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 terminate 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 y'all desire to exercise more than 1 thing in the same program? Let'due south run into what happens if we try to practise this with the modes that you have learned so far:

If you open up a file in "r" way (read), and so try to write to it:

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

You will go this error:

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

Similarly, if you open a file in "due west" mode (write), and so try to read it:

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

Y'all volition encounter this fault:

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

The same volition occur with the "a" (suspend) way.

How can nosotros solve this? To be able to read a file and perform some other operation in the same program, you demand 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, correct? This is probably what you will use in your programs, just exist sure to include simply the modes that you need to avoid potential bugs.

Sometimes files are no longer needed. Permit'south come across how yous can delete files using Python.

🔹 How to Delete Files

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

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

Especially, y'all need the remove() function. This function takes the path to the file every bit argument and deletes the file automatically.

image-56

Let's see an example. We desire to remove the file called sample_file.txt.

image-34

To do information technology, we write this code:

                import os os.remove("sample_file.txt")              
  • The offset line: import os is called an "import statement". This statement is written at the top of your file and information technology gives you access to the functions defined in the os module.
  • The 2d 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, allow's see an interesting tool... Context Managers!

🔸 Meet Context Managers

Context Managers are Python constructs that volition 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 yous cull.

Syntax

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

image-33

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

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

                with open("<path>", "<way>") as <var>:     # Working with the file...  # The file is closed hither!              

Example

Here's an example:

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

This context managing director 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 managing director to refer to the file object.

Trying to Read it Again

After the body has been completed, the file is automatically closed, then information technology can't be read without opening it again. Simply expect! We take a line that tries to read it over again, correct here below:

                with open("data/names.txt", "r+") as f:     print(f.readlines())  print(f.readlines()) # Trying to read the file once more, exterior of the context manager              

Let's run across what happens:

                Traceback (about contempo call concluding):   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, correct? The context director does all the heavy work for us, information technology is readable, and concise.

🔹 How to Handle Exceptions When Working With Files

When yous're working with files, errors can occur. Sometimes y'all may non have the necessary permissions to modify or access a file, or a file might not even exist.

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

Allow's see some of the most common exceptions (runtime errors) that yous might find when you piece of 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 fault:

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

Allow's break this error down this line by line:

  • File "<path>", line eight, 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 viii was executed in <module>.
  • f = open("names.txt"). This is the line that caused the error.
  • FileNotFoundError: [Errno two] 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 be.

💡 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 acceptable admission rights - for example filesystem permissions.

This exception is raised when yous are trying to read or change a file that don't have permission to admission. If yous endeavor to exercise then, y'all will see this error:

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

IsADirectoryError

According to the Python Documentation, this exception is:

Raised when a file performance is requested on a directory.

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

How to Handle Exceptions

To handle these exceptions, you can utilize a effort/except statement. With this statement, you tin can "tell" your program what to practise in case something unexpected happens.

This is the basic syntax:

                try: 	# Effort to run this code except <type_of_exception>: 	# If an exception of this type is raised, stop the process and leap to this cake                              

Here you lot can see an case with FileNotFoundError:

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

This basically says:

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

💡 Tip: You lot 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 shut the file automatically after the task (regardless of whether an exception was raised or non in the endeavour block) you tin add the finally cake.

                endeavor: 	# Attempt to run this code except <exception>: 	# If this exception is raised, stop the procedure immediately and jump to this block finally:  	# Do this subsequently running the lawmaking, fifty-fifty if an exception was raised              

This is an example:

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

There are many ways to customize the attempt/except/finally statement and you can fifty-fifty add an else cake to run a block of code merely 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 gear up of methods that you can use to work with them in your program.
  • Context Managers assist you work with files and manage them by endmost them automatically when a job has been completed.
  • Exception handling is key in Python. Mutual exceptions when you are working with files include FileNotFoundError, PermissionError and IsADirectoryError. They can be handled using try/except/else/finally.

I actually promise you liked my article and constitute it helpful. At present you can piece of work with files in your Python projects. Cheque out my online courses. Follow me on Twitter. ⭐️



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

riddlethund1971.blogspot.com

Source: https://www.freecodecamp.org/news/python-write-to-file-open-read-append-and-other-file-handling-functions-explained/

0 Response to "The Following Files Could Not Be Imported Because They Could Not Be Read"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel