File read and write data
Read and write files, essentially requesting the operating system to open a file object, then, the interface provided by the operating system reads data (file read) from this file object, or to write data to the file object (write file).
File Read
Use the built-in Python open()
function to rt
read a file, the following example modes:
>>> f = open('some.txt', 'rt')
This line of code says to open a file, if the file does not exist, will throw IOError
exceptions, and gives detailed information tips:
>>> f = open('undefined.txt', 'rt')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'undefined.txt'
When successfully open the file, you can use read()
the contents of the file read function:
>>> f.read()
'Hello world!'
When the data has been read, you need to call close()
to close the file. Because the file objects consume resources, the need for timely closed after use free resources.
Another way is to use the with
statement to the file is used to create a context, so the file object will automatically shut down.
Call read()
one time to read the entire contents of the time, if the contents of the file is too large, you can use read(size)
the fixed size of the circular read, read up to each size
byte content. readline()
Function, read each line of text readlines()
to read all the content, but row-returning list. Use of the three, can be selected according to the actual demand.
binary file
Read binary files, you need to use rb
the open mode:
>>> f = open('image.jpg', 'rb')
>>> f.read()
b'\xff\xd8\xff\xe0\x00\x10JFIF\x00...'
Read data from a file, you need to pay attention to the problem of coding. When coding errors, it throws UnicodeDecodeError
an exception. such as:
>>> f = open('some.txt', 'rt', encoding='ascii')
>>> f.read()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xcc in position 2: ordinal not in range(128)
In this case, usually designated for reading text encoding is not correct, we need to confirm the file encoding is correct. If an encoding error is still present, you can give open()
pass an optional function errors
parameters to handle these errors. such as:
>>> f = open('some.txt', 'rt', encoding='ascii', errors='replace')
>>> f.read()
'Un��ic��o��de��'
>>> f = open('some.txt', 'rt', encoding='ascii', errors='ignore')
>>> f.read()
'Unicode'
Use parameter errors
can handle the coding error problem, but the process will feel very bad. Advocated here is to make sure to use the correct code. Ambiguous when using the default setting (usually UTF-8).
Compressed file
Reading gzip
and bz2
when the compressed file format can be used gzip
, and bz2
modules. Both modules to open()
provide additional implementation to solve reading gzip
and bz2
problem of two compressed file formats. For example to read the compressed file, the following example:
>>> import gzip
>>> with gzip.open('some.gz', 'rt') as f:
... text=f.read()
>>> import bz2
>>> with bz2.open('some.bz2', 'rt') as f:
... text=f.read()
File Write
File write, you need to call the same open()
parameters, but specified mode wt
or wb
to indicate write text files or binary files:
>>> f = open('some.txt', 'wt')
>>> f.write('Hello, world!')
13
>>> f.close()
Data writing has been completed, the same need to call close()
to close the file object. Can also with
statement creates the context for normal close the file object.
Similarly, when writing compressed data, import gzip
or bz2
modules:
>>> import gzip
>>> with gzip.open('some.gz', 'wt') as f:
... f.write(text)
>>> import bz2
>>> with bz2.open('some.bz2', 'wt') as f:
... f.write(text)
Writing the compressed data, optional parameter compresslevel
can specify a compression level. E.g:
>>> with gzip.open('some.gz', 'wt', compresslevel=6) as f:
... f.write(text)
compresslevel
The default parameter value 9
, representing the highest level of compression. The lower the rating, the better the performance, but the lower the degree of compression.
Use w
mode open()
function, if the opened file before writing the data content, coverage will be cleared. If you want to add the contents of the file already exists in the case, use mode at
of open()
function.
Relates to the file read-write mode definitions and meanings, as follows:
mode | meaning |
---|---|
‘r’ | Read data (default) |
‘w’ | data input |
‘x’ | File exists throws an exception, does not exist, create |
‘a’ | Append written data |
‘b’ | Binary mode |
‘t’ | Text mode (default) |
‘+’ | Update files (read and write) |
Specific more details refer to the official Python documentation .
Reference material
source
- David M. Beazley;Brian K. Jones.Python Cookbook, 3rd Edtioni.O’Reilly Media.2013.
- Luciano Ramalho.Fluent Python.O'Reilly Media.2015.
- “2. Built-in Functions”.docs.python.org.Retrieved 20 January 2020.
- “gzip — Support for gzip files”.docs.python.org.Retrieved 22 January 2020.
- “bz2 — Support for bzip2 compression”.docs.python.org.Retrieved 22 January 2020.
- Liao Xuefeng. "Python Tutorial" .liaoxuefeng.com. [2020-01-18].
The above is Main Contents of.