You Do Not Have the Necessary Read, Write and Append Privileges on the Selected Network Backup Disk.

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

Welcome

Hi! If yous want to learn how to work with files in Python, and so this article is for you. Working with files is an important skill that every Python programmer should learn, so allow's get started.

In this article, you volition 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 y'all work with files.
  • and more!

Let's begin! ✨

๐Ÿ”น Working with Files: Basic Syntax

Ane of the about important functions that yous will demand to use as you work with files in Python is open() , a built-in function that opens a file and allows your plan to employ it and work with it.

This is the basic syntax:

image-48

๐Ÿ’ก Tip: These are the two almost commonly used arguments to phone call this office. There are six additional optional arguments. To learn more well-nigh them, please read this commodity 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 are trying to work with.

We commonly 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 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 binder every bit the Python script, like this:

image-7

But if the file is within a nested folder, like this:

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

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

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

๐Ÿ’ก Tip: The iii 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'southward a text file.

Second Parameter: Mode

The 2nd parameter of the open() function is the style , a cord with ane character. That single character basically tells Python what you are planning to do with the file in your program.

Modes available are:

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

You lot tin can likewise choose to open the file in:

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

To utilize text or binary way, you would need to add these characters to the main mode. For instance: "wb" means writing in binary way.

๐Ÿ’ก 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() if y'all want to utilize them because they are assigned by default. You lot can 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 practise more necessary? This is basically why modes exist.

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

๐Ÿ”ธ How to Read a File

Now that you know more than about the arguments that the open() function takes, let's see how you can open a file and shop information technology 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 example:

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

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

Well, a file object.

Let's 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 us that a file object is an object that lets u.s.a. work and interact with existing files in our Python program.

File objects have attributes, such as:

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

For example:

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

Now let's encounter how you can access the content of a file through a file object.

Methods to Read a File

For usa to exist able to piece of work file objects, we need to have a mode to "interact" with them in our programme and that is exactly what methods practise. Let's meet some of them.

Read()

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

image-11

Here we accept an example:

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

The output is:

                Nora Gino Timmy William              

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

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

Yes, it's a string!

In this instance, the entire file was printed because we did not specify a maximum number of bytes, merely we tin can do this too.

Here we have an instance:

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

The value returned is express to this number of bytes:

                Nor              

❗️Important: Y'all need to close a file after the task has been completed to free the resource associated to the file. To do this, you need to call the shut() method, similar this:

image-22

Readline() vs. Readlines()

You tin can read a file line by line with these two methods. They are slightly different, so allow's see them in item.

readline() reads i line of the file until information technology reaches the stop of that line. A trailing newline graphic symbol (\n) 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 example:

                f = open up("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 as individual elements (strings). This is the syntax:

image-21

For instance:

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

The output is:

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

Notice that in that location is a \n (newline character) at the end of each string, except the concluding one.

๐Ÿ’ก Tip: You lot tin get the same list with listing(f).

You can piece of work with this list in your programme by assigning it 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 tin also iterate over f directly (the file object) in a loop:

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

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

๐Ÿ”น How to Create a File

If you demand to create a file "dynamically" using Python, yous tin can do it with the "10" mode.

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

image-58

Here'southward 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 name is created:

image-30

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

๐Ÿ’ก Tip: The file will exist initially empty until you lot alter it.

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

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

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

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

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

๐Ÿ”ธ How to Alter a File

To modify (write to) a file, you need to use the write() method. Yous have two ways to exercise it (suspend or write) based on the mode that you lot cull to open up it with. Let's run across them in particular.

Append

"Appending" means adding something to the end of some other thing. The "a" mode allows you to open a file to append some content to information technology.

For case, if we accept this file:

image-43

And we desire to add a new line to it, we can open information technology using the "a" style (append) and so, 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

Here'southward an example:

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

๐Ÿ’ก Tip: Discover that I'thou adding \due north before the line to indicate that I want the new line to announced as a separate line, not equally 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 replace it entirely with new content. You can do this with the write() method if you open the file with the "west" mode.

Hither 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 is the result:

image-46

As you can see, opening a file with the "w" fashion and and then writing to it replaces the existing content.

๐Ÿ’ก Tip: The write() method returns the number of characters written.

If you want to write several lines at once, you can use the writelines() method, which takes a list 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.shut()              

The lines are added to the end of the file:

image-47

Open File For Multiple Operations

Now y'all know how to create, read, and write to a file, but what if yous want to practise more than ane thing in the same program? Let's see what happens if we try to practise this with the modes that you lot have learned so far:

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

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

Yous will get this error:

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

Similarly, if you open a file in "w" way (write), and then endeavour to read information technology:

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

You will encounter this error:

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

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

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

                f = open("information/names.txt", "due west+") # Read + Write              
                f = open("data/names.txt", "a+") # Read + Append              
                f = open("data/names.txt", "r+") # Read + Write              

Very useful, right? This is probably what you lot will utilize in your programs, but be sure to include only the modes that y'all need to avoid potential bugs.

Sometimes files are no longer needed. Let's come across how y'all tin can delete files using Python.

๐Ÿ”น How to Delete Files

To remove a file using Python, you demand to import a module called os which contains functions that collaborate with your operating arrangement.

๐Ÿ’ก Tip: A module is a Python file with related variables, functions, and classes.

Particularly, you lot need the remove() function. This part takes the path to the file as argument and deletes the file automatically.

image-56

Allow's see an example. We want to remove the file called sample_file.txt.

image-34

To do information technology, nosotros write this code:

                import os os.remove("sample_file.txt")              
  • The kickoff line: import os is called an "import argument". This statement is written at the meridian of your file and it gives you access to the functions defined in the os module.
  • The second line: os.remove("sample_file.txt") removes the file specified.

๐Ÿ’ก Tip: you can use an accented or a relative path.

At present that you know how to delete files, allow'due south come across an interesting tool... Context Managers!

๐Ÿ”ธ Meet Context Managers

Context Managers are Python constructs that will make your life much easier. By using them, you don't demand to remember to close a file at the end of your program and you accept admission to the file in the particular part of the program that you lot cull.

Syntax

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

image-33

๐Ÿ’ก Tip: The body of the context managing director has to be indented, but like nosotros indent loops, functions, and classes. If the code is non indented, information technology will not exist considered part of the context manager.

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

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

Example

Here's an example:

                with open up("information/names.txt", "r+") every bit 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 trunk of the context manager to refer to the file object.

Trying to Read it Again

After the body has been completed, the file is automatically closed, then it can't exist read without opening it again. Just expect! Nosotros accept a line that tries to read it once again, correct here below:

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

Let'due south encounter what happens:

                Traceback (most recent call concluding):   File "<path>", line 21, in <module>     print(f.readlines()) ValueError: I/O operation on airtight file.              

This mistake is thrown because we are trying to read a closed file. Awesome, right? The context manager does all the heavy work for the states, it is readable, and concise.

๐Ÿ”น How to Handle Exceptions When Working With Files

When you're working with files, errors can occur. Sometimes you may not have the necessary permissions to alter or admission a file, or a file might not fifty-fifty exist.

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

Let's run into some of the nearly common exceptions (runtime errors) that yous might discover when you work with files:

FileNotFoundError

According to the Python Documentation, this exception is:

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

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

                f = open("names.txt")              

Yous will see this error:

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

Let'south break this error down this line by line:

  • File "<path>", line 8, in <module>. This line tells yous that the mistake was raised when the code on the file located in <path> was running. Specifically, when line 8 was executed in <module>.
  • f = open("names.txt"). This is the line that caused the fault.
  • 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 be.

๐Ÿ’ก 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. According to the Python Documentation, this exception is:

Raised when trying to run an operation without the acceptable access rights - for case filesystem permissions.

This exception is raised when you are trying to read or modify a file that don't accept permission to access. If you attempt to do so, y'all will see this fault:

                Traceback (most recent call last):   File "<path>", line viii, in <module>     f = open("<file_path>") PermissionError: [Errno 13] 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 actually careful with the path that y'all pass as argument.

How to Handle Exceptions

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

This is the bones syntax:

                attempt: 	# Endeavour to run this code except <type_of_exception>: 	# If an exception of this type is raised, end the process and spring to this block                              

Hither you tin see an example with FileNotFoundError:

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

This basically says:

  • Try to open the file names.txt.
  • If a FileNotFoundError is thrown, don't crash! Simply print a descriptive argument 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 it doesn't exist already.

To shut the file automatically subsequently the job (regardless of whether an exception was raised or not in the effort block) y'all can add the finally block.

                try: 	# Try to run this code except <exception>: 	# If this exception is raised, finish the procedure immediately and jump to this block finally:  	# Do this after running the code, even if an exception was raised              

This is an example:

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

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

๐Ÿ’ก Tip: To larn more than about exception handling in Python, yous 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 utilize to work with them in your program.
  • Context Managers help yous work with files and manage them by closing them automatically when a task has been completed.
  • Exception handling is key in Python. Common exceptions when you are working with files include FileNotFoundError, PermissionError and IsADirectoryError. They tin exist handled using try/except/else/finally.

I actually hope you lot liked my article and found information technology helpful. At present you tin can work with files in your Python projects. Cheque out my online courses. Follow me on Twitter. ⭐️



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

cantrellperep1987.blogspot.com

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

0 Response to "You Do Not Have the Necessary Read, Write and Append Privileges on the Selected Network Backup Disk."

Publicar un comentario

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel