Python Notes (8) - File Input/Ou
2018-03-20 本文已影响16人
SilentSummer
转载请注明出处: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
.
- This told Python to open
- 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.
- It takes a string argument.
-
.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.
- If you open a file and call
- 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
andas
-
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
andas
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 isTrue
when the file is closed andFalse
otherwise. - By checking
file_object.closed
, we'll know whether our file is closed and can callclose()
on it if it's still open.
- Python file objects have a