How python uses the with statement on file objects
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!