Skip to content Skip to sidebar Skip to footer

Write Code That Reads a File and Displays the Number of Records

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

Welcome

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

In this article, yous volition 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 piece of work with files.
  • and more!

Let's begin! ✨

🔹 Working with Files: Basic Syntax

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

This is the basic syntax:

image-48

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

Commencement Parameter: File

The commencement parameter of the open up() role 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 up() function.

For example, the path in this part call:

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

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

image-7

Only if the file is inside a nested binder, similar this:

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

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

In this case, this would be the path:

                open up("data/names.txt")              

Observe that we are writing information/ start (the name of the folder followed past a /) and then names.txt (the proper noun 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.

Second Parameter: Fashion

The second parameter of the open() function is the way , a cord with i character. That single character basically tells Python what y'all are planning to practise with the file in your program.

Modes available are:

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

You can also choose to open the file in:

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

To use text or binary manner, you would need to add together these characters to the chief style. 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 demand to specify them in open up() if you desire 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 merely certain permissions based what you are planning to do with the file, right? Why should Python allow your plan to exercise more than necessary? This is basically why modes exist.

Think nearly it — allowing a program to do more than necessary tin can problematic. For example, if you merely need to read the content of a file, it can be dangerous to permit your programme to change it unexpectedly, which could potentially introduce bugs.

🔸 How to Read a File

Now that you know more about the arguments that the open() part takes, allow's see how yous can open a file and shop it in a variable to use it in your plan.

This is the basic syntax:

image-41

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

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

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

Well, a file object.

Permit's talk a petty bit about them.

File Objects

According to the Python Documentation, a file object is:

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

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

File objects have attributes, such equally:

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

For example:

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

At present allow'southward come across 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 fashion to "interact" with them in our program and that is exactly what methods practice. Let's see some of them.

Read()

The start method that you lot 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              

You tin can use the type() role to ostend that the value returned by f.read() is a cord:

                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, merely we tin can practice this as well.

Here we take an example:

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

The value returned is express to this number of bytes:

                Nor              

❗️Of import: Y'all need to close a file afterwards the task has been completed to complimentary the resource associated to the file. To do this, you demand to call the shut() method, like this:

image-22

Readline() vs. Readlines()

You tin can read a file line by line with these two methods. They are slightly different, so let's come across 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 lot tin laissez passer the size, the maximum number of characters that you lot want to include in the resulting string.

image-19

For instance:

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

The output is:

                Nora                              

This is the outset line of the file.

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

image-21

For instance:

                f = open("data/names.txt") impress(f.readlines()) f.shut()              

The output is:

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

Discover that there is a \n (newline character) at the end of each cord, except the terminal one.

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

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

                f = open("information/names.txt")  for line in f.readlines():     # Practise something with each line      f.shut()              

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

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

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

🔹 How to Create a File

If you need to create a file "dynamically" using Python, y'all tin do information technology with the "x" mode.

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

image-58

Hither'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, yous tin create a file and and then write to it dynamically using methods that y'all will learn in just a few moments.

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

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

                Traceback (nigh recent telephone call last):   File "<path>", line eight, 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 lot know how to create a file, let's see how you can change it.

🔸 How to Modify a File

To change (write to) a file, yous demand to use the write() method. You have two ways to exercise information technology (append or write) based on the style that you choose to open it with. Let's meet them in detail.

Append

"Appending" means adding something to the end of another affair. The "a" style allows you to open a file to suspend some content to it.

For example, if we have this file:

image-43

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

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

image-52

Here's an example:

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

💡 Tip: Discover that I'm adding \n before the line to signal that I want the new line to announced every bit a dissever line, not every bit 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 supercede it entirely with new content. You can practice 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("information/names.txt", "w") f.write("New Content") f.close()                              

This is the consequence:

image-46

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

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

If y'all want to write several lines at in one case, you can use the writelines() method, which takes a listing of strings. Each string represents a line to be added to the file.

Hither'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 finish 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'southward see what happens if nosotros effort to do this with the modes that you have learned then far:

If you open a file in "r" mode (read), and so 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 (near recent phone call last):   File "<path>", line nine, in <module>     f.write("New Content") io.UnsupportedOperation: not writable              

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

                f = open("information/names.txt", "westward") impress(f.readlines()) # Trying to read f.write("New Content") f.close()              

You lot volition see this error:

                Traceback (most recent phone call last):   File "<path>", line 14, in <module>     impress(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 performance in the same program, you need to add the "+" symbol to the mode, 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, just be certain to include simply the modes that yous 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 chosen os which contains functions that collaborate 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 instance. Nosotros 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 commencement line: import os is called an "import argument". This statement is written at the top of your file and it gives you lot 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 accented or a relative path.

Now that you know how to delete files, permit'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, y'all don't need to remember to shut a file at the end of your programme and you have admission to the file in the particular role of the program that you choose.

Syntax

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

image-33

💡 Tip: The trunk of the context manager has to be indented, just similar nosotros indent loops, functions, and classes. If the code is not indented, it volition not be considered part of the context director.

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

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

Instance

Here'south 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 information technology Once more

After the trunk has been completed, the file is automatically airtight, and then it tin can't be read without opening information technology again. But wait! Nosotros accept a line that tries to read it again, right hither below:

                with open("information/names.txt", "r+") every bit f:     print(f.readlines())  print(f.readlines()) # Trying to read the file again, outside of the context manager              

Allow'due south come across what happens:

                Traceback (most recent telephone 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 managing director does all the heavy piece of work for us, it is readable, and concise.

🔹 How to Handle Exceptions When Working With Files

When you're working with files, errors tin can occur. Sometimes you lot may not take the necessary permissions to change or access a file, or a file might non fifty-fifty be.

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

Permit's see some of the about common exceptions (runtime errors) that you might detect when yous 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 be.

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 run across this fault:

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

Let'due south break this error downwardly this line by line:

  • File "<path>", line 8, in <module>. This line tells y'all 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 up("names.txt"). This is the line that caused the error.
  • FileNotFoundError: [Errno ii] 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 mistake messages, right? This is a huge reward during the process of debugging.

PermissionError

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

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

This exception is raised when you are trying to read or alter a file that don't take permission to admission. If you endeavor to do and so, you will run into this error:

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

IsADirectoryError

Co-ordinate 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, and so exist really conscientious with the path that yous pass as argument.

How to Handle Exceptions

To handle these exceptions, you can use a effort/except statement. With this statement, you lot can "tell" your plan what to exercise in case something unexpected happens.

This is the bones syntax:

                try: 	# Effort to run this lawmaking except <type_of_exception>: 	# If an exception of this type is raised, terminate the process and jump to this cake                              

Here you can meet an example with FileNotFoundError:

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

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 cull how to handle the situation by writing the appropriate code in the except cake. Perhaps you could create a new file if it doesn't be already.

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

                endeavour: 	# Try to run this code except <exception>: 	# If this exception is raised, end the process immediately and bound to this block finally:  	# Do this after running the lawmaking, fifty-fifty if an exception was raised              

This is an example:

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

In that location are many means to customize the try/except/finally statement and you tin can even add an else block to run a block of code only if no exceptions were raised in the endeavour block.

💡 Tip: To learn more well-nigh exception handling in Python, you may similar to read my article: "How to Handle Exceptions in Python: A Detailed Visual Introduction".

🔸 In Summary

  • You lot can create, read, write, and delete files using Python.
  • File objects have their own set of methods that you tin can use to work with them in your programme.
  • 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. Mutual exceptions when you are working with files include FileNotFoundError, PermissionError and IsADirectoryError. They can be handled using attempt/except/else/finally.

I really hope you lot liked my article and found information technology helpful. Now y'all tin can piece of work with files in your Python projects. Check out my online courses. Follow me on Twitter. ⭐️



Learn to code for gratuitous. freeCodeCamp'south open source curriculum has helped more 40,000 people get jobs as developers. Get started

ongsuldet1943.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 "Write Code That Reads a File and Displays the Number of Records"