Python file Basic file operation details

Source: Internet
Author: User
Tags truncated
Prior to learning Python's list, tuples, collections and other knowledge, then the Python file-related knowledge to do a summary and analysis.

An open function

When we use Word, Excel, vim to the file operation, must first open the file, also in the program also need to open the file, and then the file operation, the operation of the file closed. The file opens using the open () function, creating a related object at the same time.

, basic syntax:

Open (file, mode= ' R ', Buffering=none, Encoding=none, Errors=none, Newline=none, closefd=true) parameter description: File: Represents the file name, You can use absolute and relative paths, and you can determine the file's append or override mode by mode: Indicates that the file is open buffering: sets the cache mode. 0 means no cache, 1 is cache, or greater than 1 indicates the size of the buffer, in bytes. Encoding: Indicates the encoding format of the open file errors: The parameter errors is used to indicate how the encoding and decoding errors are handled. cannot be used in binary mode. 1) when indicated as ' strict ', the coding error throws an exception ValueError. 2) Ignore the error when indicated as ' ignore '. 3) When specified as ' replace ', use a character for alternative mode, e.g. using '? ' To replace the error. 4) Other corresponding surrogateescape/xmlcharrefreplacs/backslashreplace are also available. NewLine: The parameter newline is used to control the end character of a line below the text pattern. Can be none, ' ', \n,\r,\r\n and so on. When in read mode, if the new line character is none, then it works as a generic line break pattern, meaning that when encountering \n,\r or \ r \ n, it can be used as a newline identifier and uniformly converted to \ n as the text input line break. When set to null ', it is also common line break mode work, but do not convert to \ n, enter what kind of, will remain the full input. When set to a different character, the corresponding character is judged to be the line break and is entered as-is into the text. When in output mode, if the new line character is none, all output text takes \ n as the newline character. If set to ' or \ n ', no substitution action is made. If it is another character, it is added after the character \ n as the line break. CLOSEFD: is used when a file handle is passed in, and when the exit file is used, the file handle is not closed. If a file name is passed in, this argument is not valid and must be true.

About the above mentioned mode model type is more, we do the following related introduction and summary,

Binary is used more when we are dealing with information such as images, while other parts are more in our manipulation of strings.

A simple example:

Sample file contents: I used to ask you when you came with me but you always laugh I have nothing I want to give you my pursuit and my freedom but you always laugh I have nothing oh when you come with me oh when you're walking with me the water is flowing and you're always smiling Why do I always want to be in front of you I will never have nothing 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) results: I used to ask you when you go with me but you always laugh I have nothing I want to give you my pursuit And my freedom, but you always laughed at me. Oh, when are you going to come with me, when you walk with me, the water in the flow, but you always laugh at me for nothing why do you laugh all the time why do I always want to be in your face I'll never have anything above use R mode Open, we take an attempt to write the file, Writes the contents to a 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: File not writable Traceback (most recent call last): ' d:/project/myapp/hello.py ', line 6, <module> a_file.write ("O Penstack\nmysqldba ") Io. Unsupportedoperation:not writable We try to open the file in binary mode again. View content: #!/usr/bin/env python#_*_coding:utf-8_*_a_file=open ("D:\\ Pythonfile.txt "," RB ") #去掉了编码格式readline =a_file.read () print (ReadLine) #a_File. Write (" OpenstAck\nmysqldba ") a_file.close () Result: 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 Other content, so no other mode modes are shown

After studying how we open the file, we will consider how to handle the open file, which mainly involves some methods of the file object.

Here's a brief introduction to the different methods and the relevant examples

Read operation: Read File.read () Filereadline () filereadlies () and other three ways

1. File.read () method

The parameter inside is size, which means that the size byte is read from the file, and when the default is null or negative, all bytes are read.

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 (+, ' # ')) #为了更好的展现测试结果分割 print (A_file.read (-1)) Result: ############################# ################# #测试结果1 ############################################### #我曾经问个不休 When you go with me but you always laugh I have nothing I want to give you my pursuit And my freedom, but you always laughed at me. Oh, when are you going to come with me? The water in the flow #!/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 (+, ' # ')) #为了更好的展现测试结果分割print (A_file.read ()) Results: ############################################## #测试结果2 ######################################## ####### #我曾经问个不休 When are you going to come with me but you always laugh I have nothing I want to give you my pursuit and my freedom but you always laugh I have nothing oh when you come with me oh when you walk with me the water in the flow #!/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 (+, ' # ')) #为了更好的展现测试结果分割print (A_file.read (3)) Results: ############################################## #测试结果3 # # # # # ########################################### #我曾经 #!/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 (+, ' # ')) #为了更好的展现测试结果分割print (A_file.read (15)) Results: ############################################## #测试结果4 ############################################### #我曾经问个不休 When are you going with me?

You can see 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 line includes "\ n" wrapping, and the parameter is also [size] control, and the difference between read () is that when the ReadLine () character in a row is not sufficient, only the row is read, and read () reads the contents of the other rows.

Example (the difference 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 (+, ' # ')) #为了更好的展现测试结果分割print (a_file.read) print ("Test result 2". Center (100, ' # ')) # For better presentation of test results split print (A_file.readline (100)) Results: ############################################## #测试结果1 ############### ################################ #我曾经问个不休 When you go with me but you always laugh I have nothing I want to give you my pursuit and my freedom but you always laugh ################################# ############# #测试结果2 ############################################### #我 nothing.

Example of ReadLine () method default and negative values

#!/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 (+, ' # ')) #为了更好的展现测试结果分割print (A_ File.readline ()) print ("Test result 2". Center (+, ' # ')) #为了更好的展现测试结果分割print (A_file.readline ( -1)) print ("test result 3". Center (100 , ' # ')) #为了更好的展现测试结果分割print (A_file.readline (4)) print ("Test result 4". Center (+, ' # ')) #为了更好的展现测试结果分割print (a_file.readline (10) Results: ############################################## #测试结果1 ################################################ I used to ask you when you came with me ############################################## #测试结果2 ############################################# # # #可你却总是笑我 Nothing ############################################## #测试结果3 ############################################ # # # #我要给你 ############################################## #测试结果4 ################################################ My quest and my self-

3, ReadLines () takes all the rows in the file and returns the list, if Sizeint>0 returns a row of approximately sizeint bytes, the actual read value may be larger than sizeint because a buffer is required. The specified length of bytes is read and the bytes are split 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 (+, ' # ')) #为了更好的展现测试结果分割print (A_file.readlines (14)) ########################### ################### #测试结果1 ################################################[' I used to ask you when you're going with me \ #!/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 (+, ' # ')) #为了更好的展现测试结果分割print (A_file.readlines (14)) [' I used to ask you when you came with me ', ' but you always laughed at me for nothing '] We can display the contents of other rows when we set the Sizeint value to be greater than the characters in the line

4, File.close ()

Closing a file after closing the file no longer reads and writes the file object's close () method flushes the unread information and closes the file object, after which there is no data content to perform the write.

Python automatically shuts down when a file's Reference object is reassigned to another file. It is a good practice to use the close () method to close a file.

#!/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 () writes the file to write to the content: WINNERLOOKOPENATCK

5, Flie.write ()

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

The Write () method does not add a newline character (' ') to the end of a string. The contents of the string are stored in the buffer before the file is closed or before the buffer is flushed, and you cannot see what is written 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 sequence of strings to a file. This sequence string can be generated by an iterative object, such as a list of strings. Line breaks need to be made with a newline character \ n.

#!/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.close () Results: OpenStack: 1docker 2mysqlDBA 3KVM 4

7, File.flush ()

The flush () method is used to flush the buffer, the data in the buffer is immediately written to the file, and the buffer is emptied, without the need to wait for the output buffer to write.

In general, the buffer is refreshed automatically when the file is closed, but sometimes you need to refresh it before closing, so 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 an iterator, and in the loop, the next () method is called in each loop, which returns the next line of the file and, if it reaches the end (EOF), triggers the stopiteration

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 ("%d lines-%s "% (index,line))

9, File.tell ()

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

Grammar:

Fileobject.tell (offset[, whence])

Return value Current file pointer

#!/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 you're coming with me I used to ask a question When are you coming with me? #!/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 you're coming with me I used to ask a question When are you going to come with me? I asked you when you were coming with me. I asked you when you were going with me. 162

10, File.isatty ()

The File.isatty () method detects if the file is connected to an end device, and returns True if it returns FALSE.

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 read pointer to a specified position without a return value

The Seek () method syntax is as follows:

Fileobject.seek (offset[, whence])

Offset--The starting shift, which represents the number of bytes that need to be shifted

Whence: Optional, default value is 0. Give the offset parameter a definition of where to start the offset, and 0 to start at the beginning of the file, 1 to start at the current position, and 2 for 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 (ten)) print (Afile.readline) Afile.seek (0,0) # Set starting at 0 print (Afile.readline (10)) Results: I asked you when you were coming with me. I once asked a question how do you summarize when you finish printing the first line, the next time you print from the last location, and then reset its position to print at the start position

12, File.fileno ()

The Descriptor method returns a file descriptor for an integral type (the filename, FD integer) that can be used for I/O operations of the underlying operating system. The return 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 ()) Results: 3

13, File.truncate ()

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

The truncate () method syntax is as follows:

Fileobject.truncate ([size]) parameter

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.