python learning 15-file

1. Coding format

  • The python interpreter uses unicode (memory)
  • .py files are stored on disk using UTF-8 (external memory)

2. Reading and writing files

1. Reading and writing files is commonly known as "I/O" operations

2. The built-in function open() creates a file object

file=open('a.txt','r')
print(file.readlines())   #列表  ['test\n', 'hhh']
file.close()

3. Commonly used file opening modes

According to the organization form of data in the file, the file is divided into the following two categories:

  • Text file: It stores ordinary "character" text. The default is the unicode character set. It can be opened using the Notepad program.
  • Binary file: The data content is stored in "bytes" and cannot be opened with Notepad. It must be opened with special software, for example: mp3 audio files, jpg pictures, .doc documents, etc.

Insert image description here

pre=open('img.png','rb')
las=open('copy.png','wb')
las.write(pre.read())
pre.close()
las.close()

4. Common methods of file objects

Insert image description here

5. with statement (context manager)

The with statement can automatically manage context resources. Regardless of the reason for jumping out of the with block, it can ensure that the file is closed correctly to achieve the purpose of releasing resources.

6. os, os.path module

Insert image description here
Insert image description here

Guess you like

Origin blog.csdn.net/qq_43757976/article/details/130565108