Python file management [use of open and with open]

First, the operation steps of the file
are basically three steps:
open the file, read and write the file, close the file

1. open() function

In python, use the open function to open an existing file or create a new file, the syntax is as follows:
open(name,mode)
name: the name of the opened file (the full path can be written)
mode: the model of the open file (read, write, etc.)

Example of mode parameter
insert image description here
write operation:

f = open('python.txt','w',encoding = 'utf-8') #打开文件并指定编码格式
f.write('hello world') # 文件写入
f.close() #关闭文件

Note:
w and a modes: If the file does not exist, the file will be created ; if the file exists, the w mode will be cleared before writing, and the a mode will directly append
r mode at the end: if the file does not exist, an error will be reported

Read operation-related methods
read() method: used for reading text type or binary file (picture, audio, video) data

f.read() # 读取文件中的所有内容
f.read(1024) # 读取1024个字符长度文件内容,字母或数字

Example:

f = open('python.txt','r',encoding = 'utf-8') 
contents = f.read() # 读取文件里的所有内容
print(contents)
f.close() #关闭文件

readlines() method: read all content by line, and return a list

f = open('python.txt','r',encoding = 'utf-8') 
lines = f.readlines()
for line in lines:
	print(line,end='')
f.close()

readline() method: read one line at a time, read content line by line

f = open('python.txt')
while True:
	# 读取一行内容
	content = f.readline()
	# 如果没有内容,终止
	if not content:
		break
	# 读取到内容,则输出
	print(content)
	
f.close()
	

2.with open() function

The purpose of using with is to omit the step of closing the file, so we often use with open('file name/absolute path of the file', mode) for file operations. The parameters of the mode are the same as the above
picture

common operation

with open('filename.txt','r') as f:
	content = f.read() # 文件的读操作

with open('data.txt','w')as f:
	f.write('hello world') # 文件的写操作

Guess you like

Origin blog.csdn.net/modi88/article/details/130310261