Python file operations [9]

Open the file mode

1. Text mode operation

r read-only mode [default]
w [write-only mode unreadable; does not exist, create; there is then emptied the contents of the original write new content;]
a append mode [unreadable; does not exist, create; there is an additional way places write new content;]

2 bytes manner

b represents the manner in bytes, no coding parameter encoding

rb byte read
wb byte write, the original content file empty
ab additional byte write

r file read
first create a file aa.txt write to
Here Insert Picture Description
2. open () function to open a file

In [1]: f = open('./aa.txt','r')

In [2]: mm = f.read()  #一次读文全部文件到内存中
In [4]: print mm
love
123
主动关闭文件
f.close()

Circular file objects

f = open('./aa.txt')

for line in f:
    print(line)

f.close()
[root@aliyun ~]# python3 000.py 
love

123

Third, write files

  1. w write
f = open('./aa.txt','w')
f.write('hello\nworld\nnihao\n')  针对文本模式的写,需要自己写换行符("\n")
f.close()
python3 000.py 
hello       #清空以前的内容 保存新内容
world
nihao
  1. a Append
f = open('./aa.txt','a')
f.write('hello\nworld\nnihao\n')  针对文本模式的写,需要自己写换行符("\n")
f.close()
python3 000.py 
hello
world
nihao
hello
world
nihao
~     

Fourth, the context manager

Use context manager to open a file, you can let Python automatically closes the file object, do not write f.close ()

Use the keyword with the context manager

file_name = "a.txt"
with    open(file_name, 'r', encoding='utf-8')  as f:
    # with 语句需要缩进,当代码出了这个缩进范围, with 就会帮我们关闭这个文件对象
    for line in f:
        print(line)
print("当你看到这行文字时,with 语句,已经关闭了刚才打开的文件对象")

The following operations are text
Here Insert Picture Description
Here Insert Picture Description
and is the same as above
Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description

Published 12 original articles · won praise 14 · views 1911

Guess you like

Origin blog.csdn.net/wx912820/article/details/104718210