Skip to content Skip to sidebar Skip to footer

Add Statement(S) to Read and Store ------------ // the Users Answer in Variable Again

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

Welcome

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

In this article, you lot will learn:

  • How to open up a file.
  • How to read a file.
  • How to create a file.
  • How to change 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 exist raised when you piece of work with files.
  • and more!

Permit'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 born function that opens a file and allows your programme to apply it and work with information technology.

This is the bones syntax:

image-48

💡 Tip: These are the ii nigh unremarkably used arguments to call this function. There are six additional optional arguments. To acquire more nearly them, please read this article in the documentation.

First Parameter: File

The commencement parameter of the open up() function is file , the accented or relative path to the file that you are trying to piece of 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() role.

For example, the path in this function telephone call:

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

Only contains the proper noun of the file. This tin can be used when the file that yous are trying to open is in the same directory or folder as the Python script, similar this:

image-7

Just if the file is inside a nested folder, similar this:

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

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

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 past a /) and then names.txt (the name of the file with the extension).

💡 Tip: The 3 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.

2d Parameter: Manner

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

Modes bachelor are:

  • Read ("r").
  • Suspend ("a")
  • Write ("west")
  • Create ("ten")

Yous tin also choose to open the file in:

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

To use text or binary way, yous would demand to add together these characters to the primary way. 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 y'all don't need to specify them in open() if you want to use them because they are assigned by default. You lot tin simply write open(<file>).

Why Modes?

It actually 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 than necessary? This is basically why modes exist.

Call up well-nigh it — allowing a program to exercise more than necessary tin problematic. For example, if you just need to read the content of a file, it can be unsafe to allow your program to alter it unexpectedly, which could potentially introduce bugs.

🔸 How to Read a File

Now that you know more than about the arguments that the open() office 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 instance:

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

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

Well, a file object.

Let's talk a little bit well-nigh them.

File Objects

According to the Python Documentation, a file object is:

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

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:

  • proper name: the proper noun of the file.
  • airtight: True if the file is closed. False otherwise.
  • mode: the fashion used to open the file.
image-57

For example:

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

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

Methods to Read a File

For u.s.a. to be able to piece of work file objects, we need to have a way to "collaborate" with them in our programme and that is exactly what methods do. Permit'southward see some of them.

Read()

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

image-11

Here we have an case:

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

The output is:

                Nora Gino Timmy William              

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

                impress(type(f.read()))  # Output <course 'str'>              

Aye, it's a string!

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

Here we have an instance:

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

The value returned is express to this number of bytes:

                Nor              

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

image-22

Readline() vs. Readlines()

You can read a file line past line with these two methods. They are slightly different, so let'southward encounter them in detail.

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

💡 Tip: Optionally, you can laissez passer 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 get-go line of the file.

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

image-21

For case:

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

The output is:

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

Notice that there is a \due north (newline character) at the end of each cord, except the last one.

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

Yous tin can piece of 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():     # Exercise something with each line      f.close()              

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

                f = open("information/names.txt", "r")  for line in f: 	# Do something with each line  f.close()              

Those are the chief methods used to read file objects. At present let'south see how you tin can create files.

🔹 How to Create a File

If y'all need to create a file "dynamically" using Python, you can do it with the "ten" fashion.

Let's run across how. This is the bones 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 proper noun is created:

image-30

With this mode, you tin create a file and and so write to it dynamically using methods that you lot volition learn in just a few moments.

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

A curious thing is that if you endeavour to run this line once again and a file with that proper name already exists, you will come across this error:

                Traceback (almost recent call last):   File "<path>", line 8, in <module>     f = open up("new_file.txt", "10") 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.

At present that you know how to create a file, allow's see how you can modify it.

🔸 How to Modify a File

To modify (write to) a file, you demand to use the write() method. Yous take two means to do it (append or write) based on the mode that you lot choose to open information technology with. Let'south come across them in item.

Append

"Appending" means adding something to the terminate of some other thing. The "a" mode allows you lot to open a file to append some content to it.

For example, if we accept this file:

image-43

And we want to add together a new line to information technology, nosotros tin can open up information technology using the "a" mode (suspend) and so, telephone call the write() method, passing the content that we want to suspend as argument.

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

image-52

Hither'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.shut() runs.

Write

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

Hither we take 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 run into, opening a file with the "w" mode and and then writing to information technology replaces the existing content.

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

If you desire to write several lines at once, you tin use the writelines() method, which takes a listing of strings. Each cord represents a line to exist added to the file.

Here'south an example. This is the initial file:

image-43

If we run this script:

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

The lines are added to the cease of the file:

image-47

Open File For Multiple Operations

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

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

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

Y'all will get this error:

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

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

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

You volition see this error:

                Traceback (most contempo call last):   File "<path>", line xiv, 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 some other operation in the same plan, you lot need to add the "+" symbol to the style, like this:

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

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

Sometimes files are no longer needed. Allow's run into how yous can delete files using Python.

🔹 How to Delete Files

To remove a file using Python, you demand 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.

Particularly, yous need the remove() function. This role takes the path to the file every bit statement and deletes the file automatically.

image-56

Let'south see an example. Nosotros want to remove the file called sample_file.txt.

image-34

To do it, we write this code:

                import bone 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 2nd line: os.remove("sample_file.txt") removes the file specified.

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

Now that y'all know how to delete files, let's see an interesting tool... Context Managers!

🔸 Meet Context Managers

Context Managers are Python constructs that volition brand your life much easier. By using them, you don't need to remember to shut a file at the end of your program and you accept access to the file in the item role of the plan that y'all cull.

Syntax

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

image-33

💡 Tip: The trunk of the context manager has to exist indented, just similar we indent loops, functions, and classes. If the lawmaking is non indented, information technology will not be considered part of the context manager.

When the trunk of the context director has been completed, the file closes automatically.

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

Instance

Here'southward an case:

                with open up("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

Afterwards the body has been completed, the file is automatically closed, then it tin can't be read without opening it again. Only wait! We have a line that tries to read information technology again, right here below:

                with open("information/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 (nigh recent telephone call last):   File "<path>", line 21, in <module>     print(f.readlines()) ValueError: I/O functioning on closed file.              

This fault is thrown considering nosotros are trying to read a closed file. Awesome, right? The context manager does all the heavy work for us, it is readable, and curtailed.

🔹 How to Handle Exceptions When Working With Files

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

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

Let's see some of the most common exceptions (runtime errors) that yous might observe 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 be.

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

                f = open("names.txt")              

You will see this mistake:

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

Permit'south break this error downwards this line by line:

  • File "<path>", line 8, in <module>. This line tells you lot that the fault 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 acquired 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 some other common exception when working with files. According to the Python Documentation, this exception is:

Raised when trying to run an functioning without the acceptable admission 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 admission. If y'all try to practice and so, you lot will run across this fault:

                Traceback (almost recent call last):   File "<path>", line eight, in <module>     f = open("<file_path>") PermissionError: [Errno xiii] Permission denied: 'information'              

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 tin use a try/except statement. With this argument, you tin "tell" your program what to do in example something unexpected happens.

This is the basic syntax:

                try: 	# Attempt to run this lawmaking except <type_of_exception>: 	# If an exception of this blazon is raised, finish 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:

  • Endeavour 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 advisable code in the except block. Mayhap you could create a new file if information technology doesn't be already.

To close the file automatically after the job (regardless of whether an exception was raised or non 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 case:

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

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

💡 Tip: To learn more than about exception handling in Python, you lot 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 tin use to work with them in your program.
  • Context Managers assist you piece of work with files and manage them by closing them automatically when a task has been completed.
  • Exception handling is central in Python. Common exceptions when you are working with files include FileNotFoundError, PermissionError and IsADirectoryError. They tin be handled using endeavour/except/else/finally.

I really hope you lot liked my article and found information technology helpful. Now you tin can piece of work with files in your Python projects. Bank 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

hillmanyousit.blogspot.com

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

Post a Comment for "Add Statement(S) to Read and Store ------------ // the Users Answer in Variable Again"