[Python] file operation ① ( file encoding | file operation | open file )





1. File encoding



Text/picture/audio/video content is translated into binary data through "encoding technology" and stored in disk;

  • The text is generally converted into binary data and stored through ASCII / GBK / BIG5 / UTF-8 and other encoding technologies ;
  • The picture is converted into binary data and stored through PNG / JPEG and other encoding techniques ;
  • The audio is converted into binary data and stored through PCM / AAC / MP3 and other encoding technologies ;
  • The video is converted into binary data and stored through H.264 / MP4 and other encoding technologies ;

File encoding is a rule for converting content into binary data, through which binary data can also be converted into file content;





2. Open the file



In Python, the process of manipulating files is as follows:

  • open a file
  • read and write files
  • close file

1. open function


Using the open function, you can open a file, and if the file does not exist, a new file will be created;

The prototype of the open function is as follows:

open(name, mode, encoding)
  • name parameter: the path of the file to be opened, which can include directory name and file name;
  • mode parameter: file access mode, there are the following access modes:
    • Read-only: r mode, open in read-only mode , the file pointer is at the beginning of the file, the default mode;
    • Write-only: w mode, open for writing only,
      • If the file already exists, open the file directly, edit from the starting position, and the original content will be deleted;
      • If it does not exist, a new file is created writing to ;
    • Append: a mode, open as append,
      • If the file exists, the new content will be written to the end of the file;
      • If the file does not exist, a new file is created writing to ;
  • encoding parameter: encoding format, generally set to UTF-8;

2. Code example - use the open function to open a file


Code example:

"""
文件操作 代码示例
"""

file = open("file.txt", "r", encoding="UTF-8")
print(type(file))  # <class '_io.TextIOWrapper'>

In the above code, the first parameter of the open function is the file name, the second parameter is the open mode "r", which means to open the file in read-only mode, and the third parameter indicates that the encoding of the file is UTF-8 coding;

The encoding parameter is not the third parameter, positional parameters cannot be used, and keyword parameters must be used to specify;

The type of file obtained is _io.TextIOWrapper, and the operation on the file can be completed with the help of this object;


The above code execution result:

D:\001_Develop\022_Python\Python39\python.exe D:/002_Project/011_Python/HelloPython/Hello.py
<class '_io.TextIOWrapper'>

Process finished with exit code 0

Guess you like

Origin blog.csdn.net/han1202012/article/details/131286143