The authors introduce :【 Lonely and cold 】—CSDN High quality creators in the whole stack field 、HDZ Core group members 、 Huawei cloud sharing expert Python Full stack domain bloggers 、CSDN The author of the force program
- This article has been included in Python Full stack series column :《Python Full stack basic tutorial 》
- Popular column recommendation :《Django Framework from the entry to the actual combat 》、《 A series of tutorials from introduction to mastery of crawler 》、《 Reptile advanced 》、《 Front end tutorial series 》、《tornado A dragon + A full version of the project 》.
- This column is for the majority of program users , So that everyone can do Python From entry to mastery , At the same time, there are many exercises , Consolidate learning .
- After subscribing to the column But there are more than 1000 people talking privately Python Full stack communication group ( Teaching by hand , Problem solving ); Join the group to receive Python Full stack tutorial video + Countless computer books : Basics 、Web、 Reptiles 、 Data analysis 、 visualization 、 machine learning 、 Deep learning 、 Artificial intelligence 、 Algorithm 、 Interview questions, etc .
- Join me to learn and make progress , One can walk very fast , A group of people can go further !
use open() Function to open a file , Create a file object , Call relevant methods to read and write files .
The complete syntax is :
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True)
Parameter description :
mode Specific parameter list :
summary :
Add one b The role of : Open the file in binary format ( Such as operating audio files , Picture file , Video file …), Perform the above operations .
Here are and file A list of all properties related to the object :
file Object's close() Method to refresh any information in the buffer that has not been written , And close the file , After that, no more writes can be made .
When a reference to a file object is reassigned to another file ,Python Will close previous files . use close() Method is a good habit .
Be careful : After opening a file , Be sure to close .
f = open(r’ceshi.py’,‘r+’)
f.read()
‘wumou love zhangmou’
f.read() # I can't study now , Because the cursor moved to the end after the last reading .
‘’
f.seek(0) # Adjust the cursor position to the front , Then there is content behind the cursor
0
f.read() # Now you can read the content
‘wumou love zhangmou’
f.tell() # You can view the position of the cursor
24
f.seek(0)
0
f.tell()
0
The above methods will be discussed in detail in the next section ~
write() Method to write any string to an open file .
grammar :fileObject.write(string)
read() Method reads a string of a specified length from an open file ( Add the specified string length to be read in brackets , Read all if you don't write ).
grammar :fileObject.read([count])
tell() Describe the current location of the file
grammar :fileObject.tell()
seek() Change the location of the current file
grammar :seek(offset [,from])
Parameters :
offset Variable represents the number of bytes to move
from Variable specifies the reference location .0, Beginning of expression .1, Indicates the current position .2, Indicates end ( The default is 0)
for example :seek(x,0)
: Move from the starting position, i.e. the first character of the first line of the file x Characters seek(x,1)
: Indicates to move backward from the current position x Characters seek(-x,2)
: To move forward from the end of a file x Characters
Practical explanation :
# -*- coding: utf-8 -*-
""" __author__ = Xiaoming - Code entities """
# Open a file in binary format for reading and writing . Overwrite the file if it already exists . If the file does not exist , Create a new file .
fo = open("foo.txt", "wb+")
# Write... To a file 2 Sentence
fo.write(b"blog.xiaoxiaoming.xyz!\nVery good site!\n")
seq = [b"blog.xiaoxiaoming.xyz!\n", b"Very good site!"]
fo.writelines(seq)
# Find the current location
print(" Current file location : ", fo.tell())
# Writing data , The file pointer is at the end of the file , Now redirect to the beginning of the file
fo.seek(0)
# Read 10 Characters
print(" Current file location : ", fo.tell())
str = fo.read(10)
print(" The string read is : ", str)
print(" Current file location : ", fo.tell())
# Close open files
fo.close()
foo.txt The contents of the document :
After processing a file , call f.close() To close files and free system resources , If you try to call the file again , An exception will be thrown .
>>> f.close()
>>> f.read()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: I/O operation on closed file
When processing a file object , Use with Keywords are a great way to . At the end , It will help you close the file correctly . And it's better to write than try - finally The sentence block should be short :
>>> with open('/tmp/foo.txt', 'r') as f:
... read_data = f.read()
>>> f.closed
True
file Object use open Function to create , The following table lists them file Functions commonly used by objects :
Some friends may not understand flush() The role of , In fact, we can simply understand its role as preservation . Let's explain the code :
for instance :
The content of the document is : wumou
>> f1 = open('ceshi.py','a')
>> f1.write('shuai')
5
>> f2 = open('ceshi.py','r')
>> f2.read() # You will find that you can't read the content just written in the way of addition now shuai
'wumou'
>> f1.flush() # We immediately refresh the buffer , Then you can read below . The function here is equivalent to saving after file operation
>> f2.seek(0)
0
>> f2.read()
'wumoushuai'
Practical explanation :
# -*- coding: utf-8 -*-
""" __author__ = Xiaoming - Code entities """
fo = open("tmp.txt", "r", encoding="utf-8")
# Flush buffer now ——> It can be understood as saving
fo.flush()
print(" The file named : ", fo.name)
print(" The file descriptor is : ", fo.fileno())
print(" The file is connected to a terminal device :", fo.isatty())
# next Return to the next line of the file
for index in range(5):
line = fo.readline()
print(" The first %d That's ok - %s" % (index + 1, line), end="")
print()
fo.seek(0)
for line in fo.readlines():
print(line, end="")
# Close file
fo.close()
summary :
Every time I write try … finally It's too cumbersome to close the file , therefore ,Python Introduced with Statement to automatically call close() Method , The code is as follows :
with open("tmp.txt", encoding="utf-8") as f:
for line in f:
print(line, end="")
First of all to see , When operating on a single file :
# -*- coding: utf-8 -*-
""" __author__ = Lonely and cold """
with open(file_path, mode='r') as f:
# Yes f Carry out a series of operations
# You can also perform other operations
# Jump out of with Statement is automatically executed f.close()
Then come to see , When multiple files are operated :
# -*- coding: utf-8 -*-
""" __author__ = Lonely and cold """
with open(file_path, mode='r') as f1,\
open(file_path, mode='r') as f2,\
.
.
.
open(file_path, mode='r') as fn:
# Yes f Carry out a series of operations
# You can also perform other operations
file.closed Check whether the file is closed
# Jump out of with Statement block is automatically executed f.close()
Finally, let's have a look at :
Two underlying methods :__enter__
and __exit__
# -*- coding: utf-8 -*-
""" __author__ = Lonely and cold """
class Person:
def __enter__(self): # Automatically call when entering
print('this is enter')
return ' Wu is so handsome '
def __exit__(self,exc_type,exc_val,exc_tb): # Automatically call when exiting
print("this is exit")
#with You can open the class , Manage multiple methods
a = Person()
with a as f: #with Can manage multiple software , Open multiple software .
print(111) # Let's open this class , Will automatically call __enter__ Method , And then print 111 The operation of
print(f) #f Namely __enter__ The return value of
# After that, it will automatically call __exit__ Method