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

Self taught Python 37 using file to manipulate files

編輯:Python

Python Use File Operation file


List of articles

  • Python Use File Operation file
  • One 、File Introduction of objects
  • Two 、 Use close() Method to close the operation
  • 3、 ... and 、 Usage method flush()
  • Four 、 Usage method fileno()
  • 5、 ... and 、 Usage method isatty()
  • 7、 ... and 、 Usage method read()


stay Python In the program , When using functions open() After opening a file , You can use File Object to operate on this file .


One 、File Introduction of objects

stay Python In the program , When a file is opened , You can use File Object to get all kinds of information about this file .File The attribute information in the object is shown in the following table :

attribute describe file.closed return True If the file has been closed , Otherwise return to Falsefile. mode Return the access mode of the opened file file.name Returns the name of the document

stay Python In the program , object File File operation is realized through built-in functions , The commonly used built-in functions are shown in the following table :

function function file.close( ) Close file , Cannot read after closing the file / Write operations file.flush( ) Refresh file internal buffer , Write the data of the internal buffer directly to the file , Instead of passively waiting for the output cache file. fileno( ) Returns an integer file descriptor (file descriptor, FD), It can be used as os Modular read Methods and other bottom operations file.isatty( ) If the file is connected to a terminal device, return True, Otherwise return to Falsefile.next( ) Return to the next line of the file file.read( [size] ) Read the specified number of bytes from the file , If not given or negative, all file.readline ( [size] ) Read entire line , Include “\n” character file.readlines( [hint] ) Read all the lines and return the list , If given hint>0, The sum of the returns is about hint Byte line , The actual read value may be greater than hint Big , Because the buffer needs to be filled file.seek(offset[,]whence ) Set the current location of the file file. tell( ) Return to the current location of the file file.truncate( [size] ) Intercept file , The bytes intercepted pass through size Appoint , Default to current file location file.write( str ) Write string to file , no return value file.writelines ( lines ) Write a list of sequence strings to the file , If you need a line break, you need to add a line break character to each line

For example, in the following example code , Demonstrates the process of opening a file and viewing its properties :

fo = open(" English phrases ","wb") # use wb Open the specified file in “ English phrases ”
print(" file name :",fo.name) # Show filename
print(" Is it closed :",fo.closed) # Displays whether the file is closed
print(" Access pattern :",fo.mode) # Display the access format of the file

Tips : Files can be written without the file suffix ( Can also write ). This use without absolute paths ,python The program and the file to be opened are in the same folder ! Or write the first sentence as :fo = open("E:\python text\ English phrases ","wb") ”
After execution, it will output :

Two 、 Use close() Method to close the operation

stay Python In the program , Method close( ) Used to close an open file , The closed file can no longer be read / Write operations , Otherwise it will trigger ValueError error . You can call... Multiple times in the program close() Method , When file Object is referenced to operate on another file ,Python It will automatically close the previous one file object . It is a good programming habit to close files in time , Use close() The syntax format of the method is as follows .

fileobject.close();

Method close() No parameters , There is no return value . For example, in the following example code , Demonstrates the use of close() Method to close the file operation .

fo = open(" English phrases ","wb") # use wb Open the specified file in
print(" The file named :", fo.name) # Displays the open file name
fo.close() # Close file

In the above code , Using functions open() With “wb" The way to open “ English phrases ”. And then use close() Method to close the file operation , After execution, it will output :

3、 ... and 、 Usage method flush()

stay Python In the program , Method flush() The function of is to refresh the buffer , Write the data in the buffer to the file immediately , Clear the buffer at the same time . In general , After the file is closed, the buffer will be automatically refreshed , But sometimes you need to refresh it before closing , Then you can use the method flush() Realization . Usage method flush() The syntax format of is as follows .

fileobject.flush();

Same as the previous method , Method flush() There are no parameters , There is no return value . For example, in the instance code of bomian , Demonstrates the use of flush() Method to flush the buffer .

fo = open(" Summer learning content ","wb") # use wb Open the specified file in
print(" The file named :",fo.name) # Displays the file name of the open file
fo.flush() # Refresh buffer
fo.close() # Close file

In the above code , First use the function open() With “wb” To open the file “ Summer learning content ”, Then use the method flush() Refresh buffer , Last use method close() Close file operation , After execution, it will output :

Four 、 Usage method fileno()

stay Python In the program , Method fileno() The function of is to return an integer file descriptor that can be used for the underlying operating system I/O operation . Usage method fileno() The syntax format of is as follows .

fileobject.fileno ();

Method fileno() No parameters , There is a return value , Just return an integer file descriptor . For example, in the following example code , Demonstrates how to use fileno() The process of returning a file descriptor .

fo = open(" Summer learning content .txt", "wb") # use wb Open the specified file in
print (" The file name is : ",fo.name) # Displays the file name of the open file
fid = fo.fileno() # Returns an integer file descriptor
print (" The file descriptor is : ",fid) # Show the descriptor of this file
fo.close () # Close file

In the above code , First use the function open() With “wb” To open the file “ Summer learning content .txt”, Then use the method fileno( ) Returns the integer descriptor of this file , Last use method close( ) Close file operation , After execution, it will output :,

5、 ... and 、 Usage method isatty()

stay Python In the program , Method isatty() Its function is to detect whether a file is connected to a terminal device , If so, return True, Otherwise return to False. Usage method isatty() The syntax format of is as follows .

fileobject.isatty();

Method iatty( ) No parameters , There is a return value . If connected to a terminal device, return True, Otherwise return to False. For example, in the following example code , Demonstrates how to use isatty() The process of detecting whether a file is connected to a terminal device .

fo = open(" Summer learning content .txt", "wb")
print (" The file name is : ",fo. name) # Displays the file name of the open file
ret = fo.isatty() # Check if the file is connected to a terminal device
print (" The return value is :",ret) # Display the connection detection results
fo.close() # Close file

In the above code , First use the function open( ) With “wb" To open the file “ Summer learning content .txt”, Then use the method isatty( ) Check whether this file is connected to a terminal device , Last use method close( ) Close file operation , After execution, it will output :

6、 ... and 、 Usage method next()
stay Python In the program ,File Object does not support method next( ). stay Python 3 In the program , Built in functions next( ) Call methods through iterators __next__( ) Return to the next item . In circulation , Method next( ) It will be called in every cycle. , This method returns the next line of the file . If the end is reached (EOF), The trigger StopIteration abnormal . Usage method next( ) The syntax format of is as follows .

next (iteratorl[, default])

Method next( ) No parameters , There is a return value , Returns the next line of the file . For example, in the following example generation two , Demonstrates how to use next The process of returning the contents of each line of a file .

fo = open(" Summer learning content .txt", "r") # use r Format and specify the file
print (" The file named :",fo. name) # Displays the file name of the open file
for index in range(3):
line = next (fo) # Return the contents of each line in the file
print (" The first %d That's ok ---%s" % (index, line)) # Show 3 Line file content
fo.close () # Close file

In the above code , First use the function open( ) With “r” To open the file “ Summer learning content .txt”, Then use the method next Return the contents of each line in the file , Last use method close( ) Close file operation . File summer learning content .txt The content and program will be output after execution :

7、 ... and 、 Usage method read()

stay Python In the program , To use the data information in a text file , First, you need to read the contents of this file into memory , You can read all the contents of the file at once , You can also read one line at a time . One way is read( ) The function of is to read the specified number of bytes from the target file , If the number of bytes is not given or is negative , Then read everything . Usage method read( ) The syntax format of is as follows .

file,read([sizel);

The above parameters “size” Indicates the number of bytes read from the file , The return value is the bytes read from the string . For example, in the following example code , Demonstrates how to use read( ) Read file 3 Process of byte contents .

fo = open(" Summer learning content .txt", "r+") # use r+ Open the specified file in
print (" The file named : ", fo.name) # Displays the file name of the open file
line = fo.read (3) # Read the contents of the first three bytes in the file
print (" String read : %s" %(line)) # Display the read content
fo.close() # Close file

In the above code , First use the function open() With “r+” To open the file “ Summer learning content .txt”, Then use the method red( ) Read the previous... In the target file 3 Bytes of content , Last use method close( ) Close file operation . The results are shown in the following figure :


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