Python Notes (8) - File InputOutput

xiaoxiao2021-02-28  95

转载请注明出处:http://blog.csdn.net/cxsydjn/article/details/71303892

The note covers how to apply what just learned to a real-world application: writing data to a file.

Python notes of open courses @Codecademy.

File I/O (Input/Output)

f = open("output.txt", "w") This told Python to open output.txt in "w" mode (“w” stands for “write”). It stored the result of this operation in a file object, f.Four modes "w": write-only mode"r": read-only mode"r+": read and write mode "a": append mode, which adds any new data you write to the file to the end of the file. .write(): writes to a file. It takes a string argument. str() might be used..read(): reads from a file..close(): You must close the file after writing.

Advanced Functions

.readline(): reading between the lines If you open a file and call .readline() on the file object, you’ll get the first line of the file; subsequent calls to .readline() will return successive lines. Buffering Data During the I/O process, data is buffered: this means that it is held in a temporary location before being written to the file.Python doesn’t flush the buffer. If we don’t close a file, our data will get stuck in the buffer.

with and as

A way to get Python to automatically close files.File objects contain a special pair of built-in methods: __enter__() and __exit__(). When a file object’s __exit__() method is invoked, it automatically closes the file.

Using with and as to invoke the __exit__() method, the syntax looks like this:

with open("file", "mode") as variable: # Read or write to the file.closed Python file objects have a closed attribute which is True when the file is closed and False otherwise.By checking file_object.closed, we’ll know whether our file is closed and can call close() on it if it’s still open.

External Resources

Python Files I/O
转载请注明原文地址: https://www.6miu.com/read-63930.html

最新回复(0)