(12) Basics of file processing

file handling

Small scale chopper

filehandle=open(filepath, mode=open mode of the file, encoding=character encoding)

with open('aaa.txt',mode='r',encoding='utf-8') as f:
    print(f.readable())
    print(f.read())
    f.closed
>>>True
>>>你好,世界之窗

This place uses a relative path. If an absolute path is used, the escape character r needs to be added.

The default is mode=r read-only
The above operation involves two resources

  1. The operating system needs to open the file
  2. f is a python variable

Character | Detail
---|---
r | open for reading (default)
w | open for writing, truncating the file first
a| open for writing, appending to the end of the file if it exists
b| binary mode
t|text mode (default)
+|open a disk file for updating (reading and writing)
U|universal newline mode (for backwards compatibility; should not be used in new code)

file open mode

Default is text mode

r: default open mode, read-only mode, if the file does not exist, an error will be
reported
Unreadable, if it does not exist, it will be created. If it exists, it will only append the content and not rewrite it. Pointer directly to the end, usually used for logging

with open ('aaa.txt',mode='r',encoding='utf-8') as f:
    print(f.readline())     #只读一行,并把光标移动到下一行的首位置,可连续放n行可以读取n行数据
    print(f.readlines())   #将文件内容全部读出并放于列表内
    
>>>你好,
>>>
>>>['你好,\n', '世界之窗\n', '我来了']



with open('111.txt',mode='w',encoding='utf-8') as f:
    f.write('hello')
    print(f.writable())
    
    L=['bruce',"said,he couldn't be caged"]
    print(f.writelines(L))


with open('222.txt',mode='a',encoding='utf-8') as f:
    print(f.readable())
    print(f.writable())
    f.write('你好\n 这世界,我来了')
    

a is a type of write mode,

non-text mode (b mode, i.e. binary)

For example, mp3, mp4, jpg and other formats can only use b mode, b means to operate in bytes, without considering the character encoding. When opening in b mode, the read content is byte type, and the byte type also needs to be provided when writing, and the encoding cannot be specified

with open('4.jpg',mode='rb') as f:
    print(f.readable())
    print(f.writable())
    print(f.read())
    
>>True
>>>False

"+" means that a file can be read and written at the same time

r+, read and write [readable, writable]

w+, write and read [readable, writable]

a+, write and read [readable, writable]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324909201&siteId=291194637