Python file read and write data

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 rtread 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 IOErrorexceptions, 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 withstatement 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 sizebyte 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 rbthe 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 UnicodeDecodeErroran 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 errorsparameters 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 errorscan 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 gzipand bz2when the compressed file format can be used gzip, and bz2modules. Both modules to open()provide additional implementation to solve reading gzipand bz2problem 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 wtor wbto 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 withstatement creates the context for normal close the file object.

Similarly, when writing compressed data, import gzipor bz2modules:

>>> 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 compresslevelcan specify a compression level. E.g:

>>> with gzip.open('some.gz', 'wt', compresslevel=6) as f:
...     f.write(text)

compresslevelThe 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 wmode 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 atof 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

  1. David M. Beazley;Brian K. Jones.Python Cookbook, 3rd Edtioni.O’Reilly Media.2013.
  2. Luciano Ramalho.Fluent Python.O'Reilly Media.2015.
  3. “2. Built-in Functions”.docs.python.org.Retrieved 20 January 2020.
  4. “gzip — Support for gzip files”.docs.python.org.Retrieved 22 January 2020.
  5. “bz2 — Support for bzip2 compression”.docs.python.org.Retrieved 22 January 2020.
  6. Liao Xuefeng. "Python Tutorial" .liaoxuefeng.com. [2020-01-18].

The above is Main Contents of.


Published 61 original articles · won praise 20 · views 8106

Guess you like

Origin blog.csdn.net/weixin_45642918/article/details/104073487