Python file operations

Source: Internet
Author: User
Tags python list
When we use word, excel, and vim to operate a file, we must first open the file. in programming, we also need to open the file and then operate on the file, close the file after the operation. Use the open () function to open the file and create a related object. I learned python list, tuples, collections, and other knowledge before. next I will summarize and analyze python file-related knowledge.

1. open function

When we use word, excel, and vim to operate a file, we must first open the file. in programming, we also need to open the file and then operate on the file, close the file after the operation. Use the open () function to open the file and create a related object.

, Basic syntax:

Open (file, mode = 'R', buffering = None, encoding = None, errors = None, newline = None, closefd = True) parameter description: file: indicates the file name, the absolute path and relative path can be used, and the append or overwrite mode of the file can be determined based on the mode: indicates the mode of opening the file buffering: sets the cache mode. 0 indicates no cache; 1 indicates cache; if it is greater than 1, it indicates the buffer size, in bytes. Encoding: indicates the encoding format of the open file. errors: the parameter errors is used to indicate how to handle encoding and decoding errors. It cannot be used in binary mode. 1) if it is specified as 'strict ', an exception ValueError is thrown when an encoding error occurs. 2) when it is specified as 'ignore', ignore the error. 3) when it is specified as 'replace ', use a character to replace the pattern, such '? 'To replace the error. 4) surrogateescape/xmlcharrefreplacs/backslashreplace. Newline: the newline parameter is used to control the end character of a line in text mode. It can be None, '', \ n, \ r, \ r \ n, etc. In read mode, if the new line character is None, it works as a general line break mode, which means that when \ n, \ r, or \ r \ n is encountered, it can be used as a line feed identifier, in addition, it is uniformly converted to \ n as the line break for text input. When it is set to null '', it is also a common line break mode, but it is not converted to \ n. If it is entered, it is completely input. When it is set to another character, the corresponding character will be judged as a line break, and the original text will be input. In the output mode, if the new line character is None, all output text uses \ n as the line break. If it is set to ''or \ n, no replacement action is performed. If it is another character, \ n is added to the end of the character as a line break. Closefd: used when a file handle is passed in, but when the file is exited, the file handle is not closed. If a file name is passed in, this parameter is invalid and must be set to True.

We will introduce and summarize the many modes mentioned above,

Binary is used for processing image and other information, while others are used for operating strings and other content.

Simple example:

Sample file content: I used to ask you when to come with me, but you always laugh, I have nothing, I want to give you my pursuit, my freedom, but you always laugh, I have nothing, oh, when are you going with me? oh, when are you? the water around me is flowing, but you are always laughing, I have nothing, why are you always smiling? why are you always pursuing? in front of you, I always have nothing to do with Process finished with exit? code 0 #! /Usr/bin/env python # _ * _ coding: UTF-8 _ * _ a_File = open ("D: \ pythonfile.txt", "r ", encoding = 'utf-8') readline = a_File.read () print (readline) result: I used to ask you when to come with me, but you always laugh, I have nothing, I want to give you my pursuit, my freedom, but you always laugh, I have nothing, oh, when are you going with me? oh, when are you? the water beside me is flowing, but you are always laughing, I have nothing, why are you always smiling? why are you always pursuing r used in front of you? mode enabled, we try to write the file, and the written content is the string openstack \ nMYSQLDBA #! /Usr/bin/env python # _ * _ coding: UTF-8 _ * _ a_File = open ("D: \ pythonfile.txt", "r ", encoding = 'utf-8') readline = a_File.read () print (readline) a_File.write ("openstack \ nMYSQLDBA") a_File.close () result: the file cannot write Traceback (most recent call last): File "D:/project/myapp/hello. py ", line 6, in
 
  
A_File.write ("openstack \ nMYSQLDBA") io. UnsupportedOperation: not writable. let's try another binary method to open the file and view the content :#! /Usr/bin/env python # _ * _ coding: UTF-8 _ * _ a_File = open ("D: \ pythonfile.txt", "rb ") # The encoding format readline = a_File.read () print (readline) # a_File.write ("openstack \ nMYSQLDBA") a_File.close () is removed: B '\ xe6 \ x88 \ x91 \ xe6 \ x9b \ xbe \ xe7 \ xbb \ x8f \ xe9 \ x97 \ xae \ xe4 \ xb8 \ xaa \ xe4 \ xb8 \ x8d \ xe4 \ xbc \ x91 \ xe4 \ xbd \ xa0 \ xe4 \ xbd \ x95 \ xe has many other contents, therefore, no other mode is demonstrated.
 

After studying how to open a file, we need to consider how to deal with the opened file, mainly involves some methods of file objects.

The following is a brief introduction and examples based on different methods.

Read operations: There are three methods to read: file. read () filereadline () filereadlies ().

1. file. read () method

The parameter in is size, which indicates reading size bytes from the file. if it is null by default or negative, it indicates reading all bytes,

Example:

#! /Usr/bin/env python # _ * _ coding: UTF-8 _ * _ a_File = open ("D: \ pythonfile.txt", "r ", encoding = 'utf-8') # readline = a_File.read (1) print ("test result 1 ". center (100, '#') # print (a_File.read (-1) results for better display of test results: ######################################## ####### test result 1 ############################## ################# I have never asked you when to come with me, but you always laugh at me, and I want to give you my pursuit. and my freedom, but you always smile, I have nothing. oh, when are you going with me? oh, when are you going with my feet? the water is flowing around #! /Usr/bin/env python # _ * _ coding: UTF-8 _ * _ a_File = open ("D: \ pythonfile.txt", "r ", encoding = 'utf-8') # readline = a_File.read (1) print ("test result 2 ". center (100, '#') # Split the print (a_File.read () results to better display the test results: ######################################## ####### test result 2 ############################## ################# I have never asked you when to come with me, but you always laugh at me, and I want to give you my pursuit. and my freedom, but you always smile, I have nothing. oh, when are you going with me? oh, when are you going with my feet? the water is flowing around #! /Usr/bin/env python # _ * _ coding: UTF-8 _ * _ a_File = open ("D: \ pythonfile.txt", "r ", encoding = 'utf-8') # readline = a_File.read (1) print ("test result 3 ". center (100, '#') # Split the print (a_File.read (3) results to better display the test results: ######################################## ####### test result 3 ############################## ################## I used #! /Usr/bin/env python # _ * _ coding: UTF-8 _ * _ a_File = open ("D: \ pythonfile.txt", "r ", encoding = 'utf-8') # readline = a_File.read (1) print ("test result 4 ". center (100, '#') # Split the print (a_File.read (15) results to better display the test results: ######################################## ####### test result 4 ############################## ################# I once asked you when to come with me

We can find that the read method is controlled by the number of bytes, and the control of the number of bytes affects its output.

2. readline () method

Reading the entire row includes "\ n" line feed, and the parameter is also controlled by [size]. The difference between this parameter and read () is that when a row in readline () is not enough characters, only the row is read and changed, read () reads the content of other rows.

Example (differences between the two)

#! /Usr/bin/env python # _ * _ coding: UTF-8 _ * _ a_File = open ("D: \ pythonfile.txt", "r ", encoding = 'utf-8') # readline = a_File.read (1) print ("test result 1 ". center (100, '#') # print (a_File.read (50) print ("test result 2") to better display test results ". center (100, '#') # print (a_File.readline (100) results for better display of test results: ######################################## ####### test result 1 ############################## ################# I have never asked you when to come with me, but you always laugh at me, and I want to give you my pursuit. in addition, you can always smile at your freedom ############################### ############### test result 2 ##################### ########################### I have nothing

Examples of the default value and negative value of the readline () method

#! /Usr/bin/env python # _ * _ coding: UTF-8 _ * _ a_File = open ("D: \ pythonfile.txt", "r ", encoding = 'utf-8') # readline = a_File.read (1) print ("test result 1 ". center (100, '#') # print (a_File.readline () print ("test result 2") to better display test results ". center (100, '#') # print (a_File.readline (-1) print ("test result 3") to better display test results ". center (100, '#') # print (a_File.readline (4) print ("test result 4") to better display test results ". center (100, '#') # print (a_File.readline (10) results for better display of test results: ######################################## ####### test result 1 ############################## ################## when do you come with me ############## ################################# test result 2 #### ######################################## #### but you always laugh at me and have nothing ############################# ################## test result 3 ################### ############################# I want to give it to you ####### ######################################## test result 4 ##################################### ########## my pursuit and self

3. readlines () takes all the rows in the file and returns the list. if sizeint> 0 returns a row of approximately sizeint bytes in the total row, the actual read value may be larger than sizeint, because the buffer zone is required. Read the specified length of bytes and split these bytes by row.

For example:

#! /Usr/bin/env python # _ * _ coding: UTF-8 _ * _ a_File = open ("D: \ pythonfile.txt", "r ", encoding = 'utf-8') # readline = a_File.read (1) print ("test result 1 ". center (100, '#') # print (a_File.readlines (14) to better display test results )) ######################################## ####### test result 1 ############################## ################# ['I have never asked you when to come with me \ n'] #! /Usr/bin/env python # _ * _ coding: UTF-8 _ * _ a_File = open ("D: \ pythonfile.txt", "r ", encoding = 'utf-8') # readline = a_File.read (1) print ("test result 1 ". center (100, '#') # print (a_File.readlines (14) for better display of test results ['I used to ask you when to follow me \ n ', 'but you always laugh at me with nothing \ n'] only when the sizeint value is set to be greater than the characters in the line can the content of other lines be displayed.

4. file. close ()

After closing a file, you cannot refresh the unwritten information in the close () method of the file object in the read/write operation, and close the object of the file. after that, no data content can be written.

Python is automatically disabled when the referenced object of the file is reassigned to another file. It is a good practice to close a file using the close () method.

#! /Usr/bin/env python # _ * _ coding: UTF-8 _ * _ a_File = open ("D: \ pythonfile2.txt", "w + ") # readline = a_File.read (1) a_File.write ("winnerlookopenatck") a_File.close () write the file into the write content: winnerlookopenatck

5. flie. write ()

The write () method writes a string to any open file. Note that Python strings can have binary data, not just text.

Do not add the newline character ('') to the end of the string in the write () method. Before the file is closed or the buffer is refreshed, the string content is stored in the buffer. you cannot see the written content in the file.

For example:

#!/usr/bin/env python#_*_coding:utf-8_*_a_File=open("D:\\pythonfile2.txt","w+")#readline=a_File.read(1)a_File.write("winnerlookopenatck")a_File.close()

6. file. writelines ()

The file. writelines () method is used to write a series of strings to a file. This series of strings can be generated by iterative objects, such as a string list. Line Feed \ n is required.

#! /Usr/bin/env python # _ * _ coding: UTF-8 _ * _ sed = ["openstack: 1 \ n", "docker 2 \ n ", "mysqlDBA 3 \ n", "KVM 4 \ n"] # Definition list a_File = open ("D: \ pythonfile2.txt", "w + ") # readline = a_File.read (1) a_File.writelines (sed) a_File.close () result: openstack: 1 docker 2 mysqlDBA 3KVM 4

7. file. flush ()

The flush () method is used to refresh the buffer, which immediately writes data in the buffer to the file and clears the buffer. it does not need to wait passively for the output buffer to be written.

Normally, the buffer is automatically refreshed after the file is closed, but sometimes you need to refresh it before closing it, then you can use the flush () method. No return value

For example

#!/usr/bin/env python#_*_coding:utf-8_*_sed=["openstack: 1\n","docker 2\n","mysqlDBA 3\n","KVM 4\n"] a_File=open("D:\\pythonfile2.txt","w+")#readline=a_File.read(1)a_File.writelines(sed)a_File.flush()a_File.close()

8. file. next ()

The next () method is used when the file uses the iterator. in the loop, the next () method is called in each loop. this method returns the next row of the file, if the end is reached (EOF), the StopIteration is triggered.

Example:

#! /Usr/bin/env python # _ * _ coding: UTF-8 _ * _ sed = ["openstack: 1 \ n", "docker 2 \ n ", "mysqlDBA 3 \ n", "KVM 4 \ n"] aFile = open ("D: \ pythonfile2.txt", "w +") for index in range (3 ): line = next (aFile) print ("row % d-% s" % (index, line ))

9. file. tell ()

The file. tell () method returns the current position of the file, that is, the current position of the file pointer.

Syntax:

fileObject.tell(offset[, whence])

Returns the pointer to the current file.

#! /Usr/bin/env python # _ * _ coding: UTF-8 _ * _ sed = ["openstack: 1 \ n", "docker 2 \ n ", "mysqlDBA 3 \ n", "KVM 4 \ n"] aFile = open ("D: \ pythonfile.txt", "r", encoding = "UTF-8") print (aFile. readline (30) print (aFile. tell () I used to ask you when to come with me. I used to ask you when to come with me. I used to 86 #! /Usr/bin/env python # _ * _ coding: UTF-8 _ * _ sed = ["openstack: 1 \ n", "docker 2 \ n ", "mysqlDBA 3 \ n", "KVM 4 \ n"] aFile = open ("D: \ pythonfile.txt", "r", encoding = "UTF-8") print (aFile. readline () print (aFile. tell () I used to ask you when to go with me. I used to ask you when to go with me 162.

10. file. isatty ()

The file. isatty () method checks whether a file is connected to a terminal device. If yes, True is returned; otherwise, False is returned.

Usage:

fileObject.isatty()#!/usr/bin/env python#_*_coding:utf-8_*_sed=["openstack: 1\n","docker 2\n","mysqlDBA 3\n","KVM 4\n"]aFile=open("D:\\pythonfile.txt","r",encoding="utf-8")print(aFile.isatty()) False

11. file. seek ()

The seek () method is used to move a file to read a pointer to a specified position without returning a value.

The syntax of the seek () method is as follows:

fileObject.seek(offset[, whence])

Offset -- the starting offset, that is, the number of bytes that need to be moved.

Whence: Optional. the default value is 0. Define the offset parameter, which indicates the starting position of the offset parameter. 0 indicates starting from the beginning of the file, 1 indicates starting from the current position, and 2 indicates starting from the end of the file.

#! /Usr/bin/env python # _ * _ coding: UTF-8 _ * _ sed = ["openstack: 1 \ n", "docker 2 \ n ", "mysqlDBA 3 \ n", "KVM 4 \ n"] aFile = open ("D: \ pythonfile.txt", "r", encoding = "UTF-8") print (aFile. readline (10) print (aFile. readline (10) aFile. seek (0, 0) # set the start position to 0 print (aFile. readline (10) result: I used to ask you when to come with me. I used to ask no. I used to ask why you summarized and printed the first line, next print is connected from the last position, and then print at the start position after resetting its position

12. file. fileno ()

Method returns an integer file descriptor (FD integer), which can be used for I/O operations on the underlying operating system. The returned value is a file descriptor:

#! /Usr/bin/env python # _ * _ coding: UTF-8 _ * _ sed = ["openstack: 1 \ n", "docker 2 \ n ", "mysqlDBA 3 \ n", "KVM 4 \ n"] aFile = open ("D: \ pythonfile.txt", "r", encoding = "UTF-8") print (aFile. fileno () Result: 3

13. file. truncate ()

The truncate () method is used to truncate a file. if the optional parameter size is specified, the file size is truncated. If no size is specified, it is truncated from the current position. after the truncation, all characters after the size are deleted.

The truncate () method syntax is as follows:

FileObject. truncate ([size]) parameter

The above is a detailed introduction to the file operations of python files. For more information, see other related articles in the first PHP community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.