When an Input File Is Opened, the Read Position Is Initially Set to the First Item in the File.

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

Welcome

Hello! 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 change a file.
  • How to close a file.
  • How to open up 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 y'all piece of work with files.
  • and more!

Let'southward begin! ✨

🔹 Working with Files: Bones Syntax

I of the nigh important functions that you will demand to utilize as you work with files in Python is open() , a built-in function that opens a file and allows your program to employ it and work with information technology.

This is the basic syntax:

image-48

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

First Parameter: File

The start parameter of the open() function is file , the absolute 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() 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 is in the same directory or binder as the Python script, similar 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 apply 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 information/ first (the name of the folder followed past a /) and then names.txt (the name of the file with the extension).

💡 Tip: The iii messages .txt that follow the dot in names.txt is the "extension" of the file, or its type. In this example, .txt indicates that information technology's a text file.

Second Parameter: Mode

The second parameter of the open() function is the manner , a string with one character. That single character basically tells Python what y'all are planning to do with the file in your programme.

Modes bachelor are:

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

You tin can also choose to open up the file in:

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

To use text or binary style, you would need to add these characters to the main style. For instance: "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 don't need to specify them in open() if you desire to use them considering they are assigned by default. You can but write open(<file>).

Why Modes?

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

Think most information technology — allowing a programme to do more than necessary tin can problematic. For case, if you only demand to read the content of a file, it tin exist dangerous to allow your program to change information technology unexpectedly, which could potentially introduce bugs.

🔸 How to Read a File

At present that yous know more about the arguments that the open() function takes, let's see how you lot can open a file and shop it in a variable to use information technology in your program.

This is the basic syntax:

image-41

Nosotros 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 blazon of value is returned by open up() ?

Well, a file object.

Let'south 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 usa 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 every bit:

  • name: the name of the file.
  • airtight: True if the file is closed. Simulated 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 lot tin can admission the content of a file through a file object.

Methods to Read a File

For the states to exist able to work file objects, we need to accept a fashion to "collaborate" with them in our program and that is exactly what methods do. Let's meet some of them.

Read()

The get-go method that you need to learn nearly is read() , which returns the entire content of the file every bit a cord.

image-11

Here nosotros have an example:

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

The output is:

                Nora Gino Timmy William              

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

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

Yes, it's a string!

In this case, the entire file was printed because nosotros did non specify a maximum number of bytes, merely we can do this every bit well.

Here we have an instance:

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

The value returned is limited to this number of bytes:

                Nor              

❗️Important: You demand to shut a file subsequently the task has been completed to free the resource associated to the file. To do this, you demand to telephone call the close() method, like this:

image-22

Readline() vs. Readlines()

Y'all tin can read a file line by line with these two methods. They are slightly different, so permit's meet them in item.

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

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

image-19

For case:

                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 equally private elements (strings). This is the syntax:

image-21

For instance:

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

The output is:

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

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

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

Y'all can work with this list in your plan by assigning information technology 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 straight (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'south see how y'all tin can create files.

🔹 How to Create a File

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

Allow's encounter 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", "10")              

A new file with that name is created:

image-30

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

💡 Tip: The file volition be initially empty until yous modify it.

A curious affair is that if you try to run this line again and a file with that proper name already exists, you lot will see this mistake:

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

Co-ordinate 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, allow'south see how you can modify it.

🔸 How to Alter a File

To modify (write to) a file, y'all need to employ the write() method. You have two ways to practice information technology (append or write) based on the mode that you lot cull to open it with. Allow's run across them in particular.

Append

"Appending" ways calculation something to the stop of some other thing. The "a" mode allows you to open a file to append some content to information technology.

For example, if we accept this file:

image-43

And nosotros desire to add a new line to it, nosotros can open it using the "a" fashion (append) and 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

Hither'due south an example:

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

💡 Tip: Find that I'm adding \north before the line to indicate that I want the new line to announced every bit a split line, non 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 desire to delete the content of a file and replace it entirely with new content. You can do this with the write() method if you lot 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", "due west") f.write("New Content") f.shut()                              

This is the effect:

image-46

Equally yous 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 you lot desire to write several lines at in one case, yous can use the writelines() method, which takes a list of strings. Each cord 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

At present yous know how to create, read, and write to a file, only what if you want to practise more than one thing in the aforementioned programme? Let'southward encounter what happens if we try to practice this with the modes that you have learned and so far:

If yous open a file in "r" mode (read), and and so effort to write to it:

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

You will go this error:

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

Similarly, if you lot open a file in "w" manner (write), and then effort to read it:

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

You volition meet this error:

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

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

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

                f = open("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 volition use in your programs, but be certain to include but the modes that you demand to avert potential bugs.

Sometimes files are no longer needed. Let'south see how you lot 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 organisation.

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

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

image-56

Let'southward see an instance. We 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 chosen an "import statement". This argument is written at the top of your file and information technology gives you access to the functions divers in the bone module.
  • The second line: bone.remove("sample_file.txt") removes the file specified.

💡 Tip: y'all can use an absolute or a relative path.

Now that you know how to delete files, let'southward encounter an interesting tool... Context Managers!

🔸 Meet Context Managers

Context Managers are Python constructs that will brand your life much easier. By using them, you don't need to remember to close a file at the stop of your program and you lot have access to the file in the item office of the programme that y'all choose.

Syntax

This is an example of a context manager 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 code is non indented, it will not exist considered function of the context manager.

When the trunk 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 hither!              

Example

Here'due south an example:

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

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

Trying to Read it Once more

Afterwards the body has been completed, the file is automatically airtight, and then information technology can't exist read without opening it once again. Only look! We accept a line that tries to read it over 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 director              

Let'southward see what happens:

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

This fault is thrown because we are trying to read a airtight file. Awesome, right? The context managing director does all the heavy work for united states, information technology is readable, and concise.

🔹 How to Handle Exceptions When Working With Files

When y'all're working with files, errors can occur. Sometimes y'all may not accept 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 affect the user experience.

Let'southward meet some of the well-nigh common exceptions (runtime errors) that you lot might discover when y'all work with files:

FileNotFoundError

According to the Python Documentation, this exception is:

Raised when a file or directory is requested just doesn't exist.

For case, if the file that yous're trying to open doesn't exist in your current working directory:

                f = open("names.txt")              

You volition see this fault:

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

Permit's break this mistake downward this line by line:

  • File "<path>", line eight, in <module>. This line tells you lot 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 mistake.
  • 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 exist.

💡 Tip: Python is very descriptive with the mistake messages, right? This is a huge advantage 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 operation without the adequate admission rights - for example filesystem permissions.

This exception is raised when y'all are trying to read or modify a file that don't have permission to access. If y'all try to practice and so, you lot will see this mistake:

                Traceback (most recent telephone call last):   File "<path>", line viii, in <module>     f = open up("<file_path>") PermissionError: [Errno thirteen] 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 laissez passer every bit argument.

How to Handle Exceptions

To handle these exceptions, y'all can utilize a try/except argument. With this statement, you can "tell" your program what to do 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 jump to this block                              

Hither you tin can encounter an case with FileNotFoundError:

                try:     f = open up("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 appropriate code in the except block. Perhaps you could create a new file if information technology doesn't exist already.

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

                effort: 	# Effort to run this code except <exception>: 	# If this exception is raised, end the procedure immediately and jump to this block finally:  	# Exercise 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.shut()              

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

💡 Tip: To acquire 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 lot tin create, read, write, and delete files using Python.
  • File objects have their own set of methods that yous 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 job has been completed.
  • Exception handling is key in Python. Mutual exceptions when you are working with files include FileNotFoundError, PermissionError and IsADirectoryError. They tin 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. 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 become jobs as developers. Get started

parkerhising.blogspot.com

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

0 Response to "When an Input File Is Opened, the Read Position Is Initially Set to the First Item in the File."

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel