程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

23. Python file i/o (I) [explain open() function & context manager with... As]

編輯:Python

Catalog :

  • Each preface :
  • Python file I/O( One )
    • 1.1 The basic method
      • 1.1.1 Open and close files
      • 1.1.2 file Object properties
      • 1.1.3 Knowledge point supply station
      • 1.1.4 Basic file reading, writing and positioning
      • 1.1.5 close()
      • 1.1.6 file( file ) Methods
      • 1.1.7 Context management with.......as

Each preface :

  • 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 !

Python file I/O( One )

1.1 The basic method

1.1.1 Open and close files

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 :

  • file: It's necessary , File path ( It could be an absolute path , It could be a relative path ).
  • mode: Optional , File open mode .
  • buffering: Buffer size of the deposit area . Set to 0, There will be no deposit . Set to negative , The buffer size of the deposit area is the system default . The buffer size of the default deposit area is 0.
  • encoding: In general use utf8.
  • errors: An error level .
  • newline: Distinguish line breaks .
  • closefd: Incoming file Parameter type .

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 .

1.1.2 file Object properties

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 .

1.1.3 Knowledge point supply station

  • windows In the system :
    Relative paths : Without drive letter .
    Absolute path : With drive letter .
  • Cursor position :
    1. If you finish reading, you can't read , Because the cursor is at the end
    2. adopt seek Method to reposition the cursor
    3. After writing , The cursor is at the end
    Take an example :

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 ~

1.1.4 Basic file reading, writing and positioning

  • 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 :

1.1.5 close()

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

1.1.6 file( file ) Methods

file Object use open Function to create , The following table lists them file Functions commonly used by objects :

  • call read() Will read all the contents of the file at once , If the document has 10G, Memory bursts , therefore , To be on the safe side , It can be called repeatedly read(size) Method , Read at most each time size Bytes of content .
  • call next() or readline() You can read one line at a time ,f.next() Read data line by line , and f.readline() be similar , The only difference is ,readline() If there is no data at the end of reading, it will return null , and next() If the data is not read, an error will be reported .
  • call readlines() Read everything at once and return... By line list. therefore , Decide how to call... As needed .
  • If the file is small ,read() One time reading is the most convenient ; If you can't determine the file size , Call again and again read(size) More secure ; If it's a configuration file , call readlines() Most convenient .

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 :

  • establish tmp.txt The content of the document is :
  • Code up :
# -*- 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 :

  • Persistent storage : Saving data in memory is easy to lose , It can only be stored in the hard disk for a long time , The basic method of saving in the hard disk is to write data into a file .
  • Open and close : stay python The opening and closing of files in become very simple and fast , The file will be saved automatically when it is closed .

1.1.7 Context management with…as

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="")
  • effect :
    Give Way python Automatically execute the shutdown process , That is to call close() Method .
    Manage multiple files to close automatically .

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 


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved