Get the App
SLTechnology News&Howtos  ›  Development  › 

How python uses the with statement on file objects

Shulou Source: shulou.com Published: 2022-06-01 04:52:01 10月11日 Update

Editor to share with you how to use python with statements on file objects, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

Use the with statement on the file object

When working on a project, we often read and write to the file. The most common way is to use the open () function to open a file, which creates a file object that we can manipulate, and then, as a habit, we should close the file object with close ().

F = open ('dataset.txt', 'w') f.write (' new_data') f.close ()

This is easy to remember, but sometimes after hours of writing code, we may forget to close the f file with f.close (). At this point, the with statement comes in handy. The with statement automatically closes the file object f as follows:

With open ('dataset.txt',' w') as f: f.write ('new_data')

With this, we can keep the code short.

You don't need it to read CSV files because you can easily read them with pandas's pd.read_csv (), but this is still useful when reading other types of files. For example, it is often used when reading data from an pickle file.

Import pickle # read the dataset with open ('test',' rb') as input: data = pickle.load (input) from the pickle file. These are all the contents of the article "how to use the with statement on a file object by python". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Files objects statements articles code content data short not very creative practices functions most hours regular common forms methods more useful Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Shulou Technology Shulou Information MySQL NVidia