Understand Python in one article (5) ----- files

I. Introduction

File operations play a very important role in all programming languages. File operations in programming languages ​​are all the same, nothing more than reading and writing. This article will introduce Python related file operations in detail, including common methods and methods Use, some small cases and the use of with statement for everyone to learn!

2. Methods and cases

2.1 Steps to answer questions for file operations

First, let's summarize the general steps of file operation:

  • 1. Open the file
  • 2. Operate the file, either read or write
  • 3. Close the file.
    Three steps are indispensable.

2.2 Introduction to common methods

The open() method is used to open a file and return the file object. This function is required in the process of processing the file. If the file cannot be opened, an OSError will be thrown.

  • Note: Use the open() method to ensure that the file object is closed, that is, call the close() method.
    The common form of the open() method is to receive two parameters: file name (file) and model (mode), as shown below:
open(file, mode='r')

Common open modes are:

Open mode Perform operation
‘r’ Open the file as read-only (default)
‘w’ Open the file for writing, it will overwrite the existing file
‘x’ If the file already exists, opening in this mode will cause an exception
‘a’ Open in writing mode, if the file exists, append writing to the end
‘b’ Open the file in binary mode
‘t’ Open in text mode (default)
‘+’ Read and write mode (can be added to other modes for use
'U' Universal newline support
  • The default is text mode, if you want to open in binary mode, add b.

Commonly used methods are:

method Method introduction
f.close() Close file
f.read([size = -1]) Read size characters from the file, when size is not given or a negative value is given, read all the remaining characters, and then return as a string
tell() Returns the current position of the file pointer in the file
seek(offset,from) Move the file pointer in the file, offset by offset bytes from from (0 represents the starting position of the file, 1 represents the current position, 2 represents the end of the file)
write(str) Write the string str to the file
readline([size = -1]) Read and return a line from the file (including the end of line), if size is defined, it returns size characters
writelines(seq) Write a string sequence seq to the file, seq should be an iterable object that returns a string

2.3 Introduction to common methods

First, we use a paragraph from the Romance of the Three Kingdoms as the case file data.txt.
"The billowing Yangtze River flows eastward, and the waves wash away the heroes. Success and failure turn around. The green mountains are still there, and the sunset is red for
a few times. The white-haired fisherman is on the Jiangzhu River, and he is used to watching the autumn moon and spring breeze. A pot of dirty wine meets each other in joy. , Are all talking about it with
laughter.-Sending the
first banquet of "Linjiang Fairy" Taoyuan hero three knots righteous cut the yellow turban hero first to speak of
the general trend of the world, divided for a long time must be united, together for a long time must be divided. The seven kingdoms will be divided into battle on weekends and merged into Qin. And Qin After the extinction, the Chu and Han were divided into disputes and merged into the Han. The Han Dynasty rebelled from the high ancestor cutting the white snake and unified the world. Later, Guangwu Zhongxing, passed to Emperor Xian, was divided into three kingdoms. The reason for the chaos was almost started. The two emperors Huan and Ling. Emperor Huan imprisoned kindness and worshipped eunuchs. And Emperor Huan collapsed, Emperor Ling ascended the throne, and the generals Dou Wu and Taifu Chen Fan assisted each other. Sometimes eunuchs Cao Jie and other eunuchs used power, and Dou Wu and Chen Fan tried to punish them. The situation was not secret, but it was the victim. Zhong Juan has since healed. In the
second year of Jianning, looking at the sun, the Emperor Wende Temple. The square rose, and the corner of the temple was gusty. Only a big green snake was seen. , Fei Jiang came down from the beam, and panned on the chair. The emperor was startled, left and right to enter the palace, all officials rushed to avoid. After a short while, the snake was gone. Suddenly a heavy thunder and heavy rain, hail, fell to the middle of the night, but there were countless houses damaged. In February of the fourth year of Jianning, Luoyang earthquake; water overflowed again, and coastal residents were swept into the sea by big waves. In the first year of Guanghe, the female rooster turned into a male. In June, the black air was more than ten feet away and flew into Wende. In the middle of the hall. In autumn and July, there are rainbows in Yutang; the Wuyuan mountain and shore are all cracked. All kinds of ominous, not just one end. The emperor asks the officials on the grounds of disaster, and discusses Lang and Cai Yong to sparse, thinking that the neon has become a chicken. This is the result of Fusi’s political intervention, and the words are quite straightforward. Dilan sighed and changed his clothes. Cao Jie peeked at the back and announced to the left and right; he was caught in the crime and returned to the field. Later Zhang Rang Ten people, Zhao Zhong, Feng Di, Duan Gui, Cao Jie, Hou Lan, Jian Shuo, Cheng Kuang, Xia Yun, and Guo Sheng were treacherous friends, and they were named "Ten Chang Shi". The emperor respected Zhang Rang and called it " "Father." North Korea’s politics and Japan’s failures caused the world’s people to be confused and thieves swarmed."

  • Open a file
f = open('data.txt','r',encoding = 'utf-8')
  • f.read([size = -1]): read size characters from the file, when size is not given or a negative value is given, read all the remaining characters, and then return as a string.
f.read(5)
  • readline([size = -1]): Read and return a line from the file (including the end of line), if there is a defined size, then return size characters |
f.readline()
  • tell(): Returns the current position of the file pointer in the file
f.tell()
  • seek(offset,from): Move the file pointer in the file, offset by offset bytes from from (0 represents the starting position of the file, 1 represents the current position, 2 represents the end of the file)
f.seek(45,0)
  • Note: In text files, files that are not opened with the b-mode option are only allowed to calculate the relative position from the beginning of the file, and an exception will be raised when calculating from the end of the file.

  • write(str): write the string str to the file

f = open('E:\\test.txt','w')
f.write('我爱kk')
f.close()
  • writelines(seq): Write a string sequence seq to the file, seq should be an iterable object that returns a string
f = open('E:\\test.txt','a')
f.writelines('I love KK!!!0000')
f.close()

2.3 Case:

Write the contents of the datatxt file to another file data_copy.txt.

fr = open('data.txt','rb') # 打开文件data.txt
context = fr.read() # 读取data.txt文件内容
fw = open('data_copy.txt','wb') # 打开文件data_copy.txt
fw.write(context) # 写入data_copy.txt文件
fw.close()
fr.close()

Three, the use of concise with statement

3.1 File reading and writing elementary

f = open('data.txt','w')
	for each_line in f:
		print(each_line)
f.close()

3.2 Intermediate file reading and writing

try:
	f = open('data.txt','w')
	for each_line in f:
		print(each_line)
except OSError as reason:
	print('出错了:'+str(reason))
finally:
	f.close()

3.3 File read and write advanced

try:
	with open('data.txt','w')
	for each_line in f:
		print(each_line)
except OSError as reason:
	print('出错了:'+str(reason))

Guess you like

Origin blog.csdn.net/dongjinkun/article/details/113620451