Python how to use open

Open a File in Python

In this tutorial, you’ll learn how to open a file in Python.

The data can be in the form of files such as text, csv, and binary files. To extract data from these files, Python comes with built-in functions to open a file and then read and write the file’s contents.

After reading this tutorial, you can learn: –

  • How to open a file in Python using both relative and absolute path
  • Different file access modes for opening a file
  • How to open a file for reading, writing, and appending.
  • How to open a file using the with statement
  • Importance of closing a file

Table of contents

Access Modes for Opening a file

The access mode parameter in the open() function primarily mentions the purpose of opening the file or the type of operation we are planning to do with the file after opening. in Python, the following are the different characters that we use for mentioning the file opening modes.

sample text file

# Opening the file with absolute path fp = open(r'E:\demos\files\sample.txt', 'r') # read file print(fp.read()) # Closing the file after reading fp.close() # path if you using MacOs # fp = open(r"/Users/myfiles/sample.txt", "r")
Welcome to PYnative.com This is a sample.txt

Opening a File with Relative Path

A relative path is a path that starts with the working directory or the current directory and then will start looking for the file from that directory to the file name.

For example, reports/sample.txt is a relative path. In the relative path, it will look for a file into the directory where this script is running.

# Opening the file with relative path try: fp = open("sample.txt", "r") print(fp.read()) fp.close() except FileNotFoundError: print("Please check the path.")

Handling the FileNotFoundError

In case we are trying to open a file that is not present in the mentioned path then we will get a FileNotFoundError .

fp = open(r'E:\demos\files\reports.txt', 'r') print(f.read())
FileNotFoundError: [Errno 2] No such file or directory: 'E:\demos\files\reports.txt'

We can handle the file not found error inside the try-except block. Let us see an example for the same. Use except block to specify the action to be taken when the specified file is not present.

try: fp = open(r'E:\PYnative\reports\samples.txt', 'r') print(fp.read()) fp.close() except IOError: print("File not found. Please check the path.") finally: print("Exit")
File not found. Please check the path. Exit

File open() function

Python provides a set of inbuilt functions available in the interpreter, and it is always available. We don’t have to import any module for that. We can open a file using the built-in function open().

Syntax of the file open() function

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

It return the file object which we can sue to read or write to a file.

Читайте также:  Html forms background color

Let us see the parameters we can pass to the open() function to enhance the file operation.

sample text file after writing

Closing a File

We need to make sure that the file will be closed properly after completing the file operation. It is a bad practice to leave your files open.

In Python, It is very important to close a file once the job is done mainly for the following reasons: –

  • It releases the resources that have been tied up with the file. By this space in the RAM can be better utilized and ensures a better performance.
  • It ensures better garbage collection.
  • There is a limit to the number of open files in an application. It is always better to close the file to ensure that the limit is not crossed.
  • If you open the file in write or read-write mode, you don’t know when data is flushed.

A file can be closed just by calling the close() function as follows.

# Opening the file to read the contents f = open("sample2.txt", "r") print(f.read()) # Closing the file once our job is done f.close()

Opening file using with statement

We can open a file using the with statement along with the open function. The general syntax is as follows.

with open(__file__, accessmode) as f:

The following are the main advantages of opening a file using the with statement

  • The with statement simplifies exception handling by encapsulating common preparation and cleanup tasks.
  • This also ensures that a file is automatically closed after leaving the block.
  • As the file is closed automatically it ensures that all the resources that are tied up with the file are released.

Let us see how we can the with statement for opening a file with an example. Consider there are two files ‘sample.txt’ and ‘sample2.txt’ and we want to copy the contents of the first file to the second.

# Opening file with open('sample.txt', 'r', encoding='utf-8') as infile, open('sample2.txt', 'w') as outfile: # read sample.txt an and write its content into sample2.txt for line in infile: outfile.write(line) # Opening the file to read the contents f = open("Sample2.txt", "r") print(f.read()) f.close()
Welcome to PYnative.com File created to demonstrate file handling in Python

Here we can see that the contents of the sample2.txt has been replaced by the contents of sample.txt.

Creating a new file

We can create a new file using the open() function by setting the x mode. This method will ensure that the file doesn’t already exist and then create a new file. It will raise the FileExistsError if the file already exists.

Example: Creating a new file.

try: # Creating a new file with open("sample3.txt", "x") as fp: fp.write("Hello World! I am a new file") # reading the contents of the new file fp = open("sample3.txt", "r") print(fp.read()) except FileExistsError: print("The file already exists")
Hello World! I am a new file

Opening a File for multiple operations

In Python, we can open a file for performing multiple operations simultaneously by using the ‘+’ operator. When we pass r+ mode then it will enable both reading and writing options in the file. Let us see this with an example.

with open("Sample3.txt", "r+") as fp: # reading the contents before writing print(fp.read()) # Writing new content to this file fp.write("\nAdding this new content")

Opening a Binary file

Binary files are basically the ones with data in the Byte format (0’s and 1’s). This generally doesn’t contain the EOL(End of Line) so it is important to check that condition before reading the contents of the file.

Читайте также:  Css media screen orientation

We can open and read the contents of the binary file as below.

with open("sample.bin", "rb") as f: byte_content = f.read(1) while byte_content: # Printing the contents of the file print(byte_content) 

Summary

In this tutorial, we have covered how to open a file using the different access modes. Also, we learned the importance of opening a file using the ‘with’ statement.

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Источник

How to Open Files in Python

Python gives us file handling methods within its standard library. This is really convenient as a developer since you do not really need to import any more modules for handling files.

The key methods provided to us by the Python for file handling are open() , close() , write() , read() , seek() and append() .

Let’s go over the open() method that allows us to open files in Python in different modes.

Open Files in Python

To open a file, all we need is the directory path that the file is located in. If it’s located in the same directory then including just the complete filename will suffice.

I’ve created a file with some sample text in it which we’ll use as a sample to learn the open file method.

Python Open File Sample File Contents

1. Opening a file using the open() method

To open the OpenFile.txt and read the text contents of the file, let’s use the open() and the read() methods.

file = open('OpenFile.txt') print(file.read()) file.close()

The read() method will read the entire contents of the file.

Python Open File Output

By default, the open() method opens a file in read-only mode. To write to a file, we will need to specify that the file has to be opened in write mode.

2. Different Modes For open() Method

Let’s try to write to the file with the default mode on.

file = open('OpenFile.txt') print(file.read()) file.write("testing write") file.close()

We’ll keep the read operation as it is so we can see where the code stops.

File Write Not Permitted Read Only Mode

So what are modes, and how do we add them? Below is a list of modes when using the open() method.

  • r: Read-Only mode.
  • r+: Read and write mode. Will not create a new file and open will fail if the file does not exist
  • rb: Read-only binary mode to read images, videos, etc.
  • w: Write-only mode. Overwrites existing file content. This will create a new file if the specified filename does not exist.
  • w+: Read and write mode.
  • wb: Binary write-only mode for writing to media files.
  • wb+: Binary read and write mode.
  • a: Append mode. Does not overwrite existing content
  • a+: Append and read mode. It will create a new file if the filename does not exist.
  • ab: Append binary mode for images, videos, etc.
  • ab+: Append and read binary mode.
Читайте также:  Including css file in javascript

3. Opening Files in Write Mode in Python

There are multiple ways you can open a file in write mode in Python. Depending on how you want the file handling methods to write to a file, you can use one of the below modes.

file = open('OpenFile.txt', 'w') print(file.read()) file.close()

By adding the ‘w’ while opening the file in the first line, we specify that the file should be opened in write mode. But this operation would fail too because the file is write-only and won’t allow us to use the read() method.

Write Only Mode File Not Readable

file = open('OpenFile.txt', 'w') file.write('New content\n') file.close()

The above code will completely clear all the contents of the text file and instead just say “New content”.

If you do not want to overwrite the file, you can use the a+ or r+ modes.

The r+ mode will write any content passed to the write() method.

file = open('OpenFile.txt', 'r+') print(file.read()) file.write('r+ method, adds a line\n') file.close()

The a or a+ mode will perform the same action as the r+ mode with one main difference.

In the case of the r+ method, a new file will not be created if the filename specified does not exist. But with a+ mode, a new file will be created if the specified file is not available.

4. Opening Files Using the with clause

When reading files with the open() method, you always need to make sure that the close() method is called to avoid memory leaks. As a developer, you could miss out on adding the close() method causing your program to leak file memory due to the file being open.

With smaller files, there isn’t a very noticeable effect on the system resources but it would show up when working with larger files.

with open('OpenFile.txt', 'r+') as file: print(file.read())

Python Open File Output

In the above example, the output would be the same as the ones we saw in the beginning, but we don’t have to close the file.

A with block acquires a lock as soon as it’s executed and releases the lock once the block ends.

You can also run other methods on the data while staying within the with code block. I’ve edited the OpenFile.txt, in this case, and added some more text for better understanding.

with open('OpenFile.txt', 'r+') as file: lines = file.readlines() for line in lines: print(line.split())

With Command Open File Python

The with statement does the memory handling for us as long as we continue to work within its scope. This is yet another but the better way to work with files in Python.

Conclusion

You should now have a grasp on how to open a file in Python and handle the different modes for opening a file with the open() method. We’ll cover further file handling methods in upcoming tutorials.

Источник

Оцените статью