Procedure for file operation
- Open the file, get the file handle and assign a value to a variable
- Manipulating a file with a handle
- Close File
Basic operations
12345678 |
f
=
open
(
‘lyrics‘
)
#打开文件
first_line
= f.readline()
print
(
‘first line:‘
,first_line)
#读一行
print
(
‘我是分隔线‘
.center(
50
,
‘-‘
))
data
=
f.read()
# 读取剩下的所有内容,文件大时不要用
print
(data)
#打印文件
f.close()
#关闭文件
|
The mode of opening the file is:
- r, read-only Mode (default).
- w, write-only Mode. "unreadable; not exist; create; Delete content;"
- a, Append Mode. "readable; not exist" create; "only append content;"
"+" means you can read and write a file at the same time
- r+, can read and write Files. "readable; writable; can be added"
- w+, Write and read
- A +, with a
"U" means that the \ r \ n \ r \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ r or r+ mode can be converted automatically when reading
"b" means processing binary files (E.G. ftp send upload ISO image file, Linux can be ignored, Windows process binary file should be Labeled)
With statement
To avoid forgetting to close a file after opening it, you can manage the context by:
123 |
with open ( ‘log‘ , ‘r‘ ) as f: ... |
This way, when the with code block finishes executing, the internal automatically shuts down and frees the file Resource.
After Python 2.7, with also supports the management of multiple file contexts simultaneously, namely:
12 |
with open ( ‘log1‘ ) as obj1, open ( ‘log2‘ ) as obj2: pass |
Python file operations