Python file reading and writing study notes []

1 read file

1.1 Reading a text file

Read file generally includes three steps:

try:
    F = Open ( ' / path / to / File ' , ' R & lt ' ) to open the file #
     Print (reached, f.read ()) reads the contents of the file #
 the finally :
     IF F:
        f.close () # close the connection

Shorthand: [Python introduced a withstatement to help us to automatically call the close()method, and before the try ... finally ... close ()]

with open('/path/to/file', 'r') as f:
    print(f.read())

 

File reading method:

  • If the file is small, read()one-time reading most convenient;
  • If you can not determine the file size, repeatedly calling read(size)safer: Each read up to size bytes of content
  • Use readline()can read each line of content
  • If the configuration file, calls the readlines()most convenient: one read all the contents and press OK to returnlist

 1.2 read binary files (audio and video)

>>> f = open('/Users/michael/test.jpg', 'rb')

 1.3 指定读取文件的字符编码

>>> f = open('/Users/michael/gbk.txt', 'r', encoding='gbk')

针对包含有非法编码字符的文件,可能遇到UnicodeDecoderError,可通过open函数的errors=’ignore‘忽略
>>> f = open('/Users/michael/gbk.txt', 'r', encoding='gbk', errors='ignore') 

 

2 write file

The method of the same document, which is a schematic of w

Recommendations with the wording:

with open('/Users/michael/test.txt', 'w') as f:
    f.write('Hello, world!')

Note: When you write a file, the operating system does not directly write data to disk, but cached into memory, free time and then slowly write. If you do not call the close () method, the operating system does not directly cached data in memory is written to disk, there may be some data loss.

  • w: covering the existing file
  • a: the presence of additional files after

 

3 memory read and write

  • String read StringIO
  • Binary data read and write BytesIO

Reference: https://www.liaoxuefeng.com/wiki/1016959663602400/1017609424203904

Guess you like

Origin www.cnblogs.com/wooluwalker/p/12243225.html