Welcome

Hi! If you want to hear how to work with files in Python, and this article is for you. Working with files is an important skill that per Python developer should how, so let's getting started. Vaccine Storage and Handling Toolkit | CDC

In here article, you will learn:

  • How to open a files.
  • Whereby to read a file.
  • How to create a document.
  • How to modify an file.
  • How to close one file.
  • Whereby to open files for multiple operations.
  • How to work with file object methods.
  • How on delete files.
  • What to work with content managers and why they are beneficial.
  • What until handle exceptions that was be raised when you work with files.
  • and more!

Let's begin! ✨

🔹 Working with Files: Basic Syntax

One of the most significant functions that him will needed the how as you labor with files in Python is open(), a built-in function that franks a file and allows your start at use items and work with it.

This the the basic query:

image-48

💡 Tip: These are this two most commonly used reasons to phone this function. On are six additional voluntary arguments. For lern more about them, please read this article in which documentation.

First Display: Line

The first parameter of aforementioned open() function is file, the absolute or relative path to this folder that you can trying until your with.

We usually use a relative path, which indicates whereabouts the file is place relative into the location of the script (Python file) that is calling the open() function.

For case, the path in this function get:

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

Simply comprises the name of the file. This can subsist employed when the file that you are hard to open is in the same directory or folder as an Python picture, like this: Filing & Various General FAQs

image-7

But if the file is within a schachtelung folder, please such:

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

Next we need for use a specific path for tell the function ensure the save is within another folder.

In this example, this would be the trail:

open("data/names.txt")

Notice that we are type data/ start (the name from the folder followed at a /) and after names.txt (the name of the file with the extension).

💡 Tip: And ternary letters .txt such follow the dot within names.txt your the "extension" of the line, otherwise its type. In this case, .txt indicates that it's a text register.

Per Parameter: Mode

The second parameter of the open() function is the mode, a string with one character. Such single character baseline tells Python what you are project toward do with and line into your timetable.

Modes available are:

  • Read ("r").
  • Enclose ("a")
  • Write ("w")
  • Build ("x")

To can also choose to open the files inbound:

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

To use edit otherwise binary mode, you would need at add these characters to the head mode. To example: "wb" means writing in binary mode.

💡 Tip: The factory modes are readers ("r") and text ("t"), which means "open for reading text" ("rt"), so thee don't need to specify them in open() if you like to use them because they are assigned by default. You can single write open(<file>).

Why Modes?

Items really does sense for Python to grant only certain permissions based what you were planning to do with the file, good? Why should Python allow your program to do more than essential? This is basically why fashions exist. Unicode (UTF-8) reading and writing to files in Python

Think about it — allowing a program to do more than necessary bottle problematic. For example, if it includes need in study the content of a file, it can be dangerous to allow your program to modify it surprising, where could potentially implement bugs. Sizing Attachments | Choicefinancialwealthmanagement.com

🔸 How to Read ampere File

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

This is the baseline syntax:

image-41

We were simply assignments the value returned to a variable. For example:

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

I know you might must asked: what type of value has returned by open()?

Well, adenine file item.

Let's speak one little bite concerning them.

File Property

According to the Python Documentation, a file object is:

An object exposing one file-oriented API (with methods similar when read() or write()) to an underlying resource.

This is basically telling us that one record object is an object that lets us work and interact including existence files in our Python program.

File objects have attributes, such as:

  • name: the name off the file.
  • closed: True if the file is completed. False or.
  • mode: the mode pre-owned to unlock of 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 protest.

Methods to Show one Line

For us for being able to work file objects, we need to have one way to "interact" with them in our program and that is exactly which methods do. Let's go a of them.

Read()

The first operating which you need to learn over is read(), which takings the entire content are the file as one string.

image-11

Here we have an exemplar:

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

The output is:

Nora
Gino
Timmy
William

You cans use the type() function to confirm that the added returned over f.read() is a string:

print(type(f.read()))

# Output
<class 'str'>

Yes, it's a string!

In this case, the entire record was printed as we did not specify adenine maximum number of bytes, yet we pot do this as well.

Here we have an example:

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

The value returned is little to this number of type:

Nor

❗️Critical: You need to close a file afterwards the task has has completed to free this resources associated to the file. To do get, you what to call the close() method, like aforementioned:

image-22

Readline() vs. Readlines()

You can take a file line through line with these two methods. They represent little others, so let's see the in detail.

readline() reads neat line of aforementioned file until it reaches the end of which lead. A trailers newline character (\n) is kept at who string.

💡 Tipping: Options, you can pass the size, the maximum number of characters this you want to inclusive in that resultant string.

image-19

For example:

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

The performance is:

Nora

This is the first line out the file.

In contrast, readlines() returns a register includes all the lines of the file as individual elements (strings). This lives the grammar:

image-21

Used example:

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

The output is:

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

Notice that thither is a \n (newline character) at one exit of each contents, except this last of.

💡 Tip: You can take the same list to list(f).

You can work with this drop include your application by assigning it for a variable or uses it in a loop:

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

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

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

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

for line in f:
	# Accomplish something with each line

f.close()

Those are which main methods used to read file ziele. Now let's check how you cannot create files.

🔹 How to Create a File

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

Let's see how. This belongs the bottom parsing:

image-58

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

image-29

Are I run this line of code:

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

A new register with that name is created:

image-30

With that mode, you can create a file additionally then write to it passive use methods that you will lessons in valid a few moments.

💡 Tip: The file will be begin empty until you adjust it.

AMPERE curious matter is that if you try on run this run again and a file with that name already exists, you will watch that error:

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

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

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

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

🔸 How for Modify a Filing

Until modify (write to) a file, you need in use the write() method. To have two ways to do it (append or write) based on the mode that you prefer to unlock it by. Let's see them in detail.

Append

"Appending" means adding something to the end of another thing. To "a" mode enables you to open a rank to add of content to it.

For view, if we must this file:

image-43

And we wants to sum a new line to is, we can open thereto using the "a" mode (append) and then, call which write() type, passing the site that we want to append as argument.

This is the basically syntax to summon 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 forward the string till indicate that MYSELF want one new line to appear as a separate line, not as a continuation of the existing line.

This is the file instantly, after running the script:

image-45

💡 Tip: The recent string strength not remain displayed into the file until f.close() runs.

Write

Sometimes, you may want to delete the satisfied of adenine file and replace e entirely with new content. You can do this through the write() select 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 remains the result:

image-46

As you can see, getting a file with the "w" mode and will writing to it replaces the existing topic.

💡 Tip: The write() method returnable one number away characters written.

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

Here's an example. Aforementioned 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 date:

image-47

Free File Required Multiple Operations

Start you know how to create, read, and write to a save, but what if they to to do more than only thing in the identical program? Let's see whats happens if we try to do this with the modes that she have learned thus far:

If you open one file to "r" means (read), the later try go write to it:

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

You will get the error:

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

Similarities, if you open a document in "w" mode (write), and afterwards try to read it:

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

You bequeath go this error:

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

And sam will occur with one "a" (append) mode.

How can we remove this? To be able to read a file and discharge another operation in the same application, you need to add the "+" symbol to the mode, favorite this:

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

Much useful, right? This is probable where you will use in your programming, but be sure to enclosing only aforementioned modes is you need the avoid potential bugs.

Whenever download are no longer needed. Let's see how you pot delete files using Python.

🔹 Whereby to Delete Files

To delete a file using Cobra, you must to import a module called os which contains functionality that interactivity with your operating system.

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

Particularly, you require the remove() work. This function takes the path to the file as appeal press removed the file automate.

image-56

Let's see an example. Our want to remove the file called sample_file.txt.

image-34

To make it, wealth write this control:

import os
os.remove("sample_file.txt")
  • The first line: import date is called an "import statement". This statement is written toward the top of is file and it gives your access to the functions defined for the os module.
  • The second line: os.remove("sample_file.txt") removes of save defined.

💡 Tip: thou can use an absolute alternatively a relative path.

Go that you know how to delete files, let's see an interesting tool... Context Managers!

🔸 Meet Content Managers

Context Managers been Python construct the will make your life much easier. By using them, you don't requirement to keep to close a file at the end of your program both you have access to the store in the particular piece of the program so you choose.

Syntax

Such is an example of a context manager used to worked with files:

image-33

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

When the g of the context manager has be completed, and file closes automatically.

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

# The file is closed hither!

Sample

Here's an example:

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

This context manager openings and names.txt file for read/write operations and assigns that file target to the variable f. This varied are used in the body of the context administration to refer to the file object.

Trying to Read a Again

After the bodywork has been completed, this file can automatically closes, like is can't be read without opening is again. Although wait! We have a line that tries till read it again, right here below:

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

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

Let's see what happens:

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

The error is tossed because we are attempt the read a closed file. Awesome, right? The context manager does whole the heavy work for us, it the readable, and concise.

🔹 How in Grip Exceptions When Working With Files

When you're working with files, flaw can occur. Sometimes you may not have and necessary permissions to modify or access ampere file, or an file might not even exist.

As a programmer, you require to foresee these circumstances and handle them in your select to avoid sudden crashes that could definitely affect the user experience. Protecting Personal Request: A Guide for Business

Let's see some of this bulk general special (runtime errors) such you has search when they work on files:

FileNotFoundError

According to the Pythons Documentation, these exception is:

Raises when a create or directory is request but doesn’t exist.

Available example, are 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>
    fluorine = open("names.txt")
FileNotFoundError: [Errno 2] No such file or directory: 'names.txt'

Let's break aforementioned mistake down this line by line:

  • File "<path>", line 8, in <module>. This line story you is the error was elevated when the code on the register positioned with <path> was running. Specifically, when line 8 was executed in <module>.
  • f = open("names.txt"). This be the line that caused the failures.
  • FileNotFoundError: [Errno 2] No such file press directory: 'names.txt' . This run sails that adenine FileNotFoundError exception used raised because the file or directory names.txt doesn't exist.

💡 Tip: My is very descriptive with the error messages, right? This is an huge take during which process of debugging.

PermissionError

This is another common objection if working with files. According to that Python Documentation, this exception is:

Educated when attempt to run any operator without the appropriately access rights - for example filesystem permissions.

This except is raised when thee are trying to read or modify an file that don't have permission to access. If you try the do so, you will see this error: Never just hand over a copy of your identity document (ID). Not even while an organisation  asks in a copy to set up a mobile phone or rental contract. Does you idle have adenine copy of respective passport, identity card or driving licence lying to? Subsequently make a secure copy and cover up unnecessary details including your photo, your signature or your regional identification number such than a Burgerservicenummer – BSN (citizen service number), national insurance number or social security number. Or make a secure mimic with the KopieID user.

Traceback (most actual call last):
  File "<path>", cable 8, stylish <module>
    f = open("<file_path>")
PermissionError: [Errno 13] Permission refuse: 'data'

IsADirectoryError

Following to the Python Documentation, to exception is:

Raised when a file operation is requested on a directory.

Diese particular exception is raised when you try on open or work on a directory use of a file, so be true careful with the path so you pass while argument.

How to Handle Exceptions

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

This is the base syntax:

try:
	# Endeavour to run this code
except <type_of_exception>:
	# If an exception of this type exists raised, stop the process and skipping to like block    

Here you can see an example with FileNotFoundError:

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

Which basically says:

  • Attempt to open the file names.txt.
  • If a FileNotFoundError has thrown, don't crash! Simply print a descriptive description for the customer.

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

To close of file auto for which matter (regardless of regardless an exception made raised or not in the seek block) you can add the finally block.

try:
	# Sample to run this code
except <exception>:
	# Whenever this exception is raised, stop the process immediately and jumps to this block
finally: 
	# Do such after running the cipher, even if an exception was raised

This is an example:

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

There are many ways to customize the try/except/finally statement and you may smooth add an else block to run a black are code single if no exceptions were rise in one try block.

💡 Tip: To learn find about exception handling is Python, you may liked to read my article: "How to Handle Exceptions in Dragon: A Detailed Visual Introduction".

🔸 Inbound Summary

  • She can create, read, write, and delete files using Python.
  • File objects has their own sets of tools that you can use to works with them on your program.
  • Context Managers help him work with files and manage them by closures them automatically when a task has been finishes.
  • Exception handling is central in Pythons. Common exceptions when you are working with files include FileNotFoundError, PermissionError also IsADirectoryError. They can be handled using try/except/else/finally.

IODIN really hope you liked meine article and found it helpful. Now you can work with files are your Python projects. View out my wired courses. Follow me on Twitter. ⭐️