A summary of Python read and write file methods

Source: Internet
Author: User
Tags readline in python

This example summarizes the Python read-write file method. Share to everyone for your reference. The specific analysis is as follows:

1.open

Always remember to call the close () method of the file object when you open the file with the. For example, you can use the Try/finally statement to ensure that the file is finally closed.

?

1 2 3 4 5 File_object = open (' thefile.txt ') Try:all_the_text = File_object.read () finally:file_object.close ()

Note: The Open statement cannot be placed in a try block because the close () method cannot be executed by the file object File_object when an exception is opened.

2. Read the document

Read a text file

?

1 2 3 input = open (' Data ', ' r ') #第二个参数默认为r input = open (' Data ')

Read binary files

Copy code code as follows:

input = open (' Data ', ' RB ')

Read all content

?

1 2 3 4 5 File_object = open (' thefile.txt ') Try:all_the_text = File_object.read () finally:file_object.close ()

Read fixed bytes

?

1 2 3 4 5 6 7 8 9 File_object = open (' Abinfile ', ' RB ') try:while True:chunk = file_object.read (MB) if not chunk:break Do_something_with ( Chunk) Finally:file_object.close ()

Read each line

Copy code code as follows:

List_of_all_the_lines = File_object.readlines ()

If the file is a text file, you can also traverse the file object to get each line:

?

1 2 For line on File_object:process line

3. Write a document

Write a text file

Copy code code as follows:

Output = open (' Data ', ' W ')

Write binary files

Copy code code as follows:

Output = open (' Data ', ' WB ')

Append Write file

Copy code code as follows:

Output = open (' Data ', ' w+ ')

Write Data

?

1 2 3 File_object = open (' Thefile.txt ', ' W ') File_object.write (All_the_text) file_object.close ()

Write Multiple lines

Copy code code as follows:

File_object.writelines (list_of_text_strings)

Note that calling Writelines writes to multiple lines is higher in performance than write-once writes.

While processing the log file, it is often the case that the log file is huge and it is impossible to read the entire file into memory at once, such as the need to process a 2GB log file on a machine with a physical memory of 2GB, and we may want to process only 200MB of content at a time.

In Python, the built-in File object directly provides a readlines (sizehint) function to accomplish such a thing. Take the following code as an example:

?

1 2 3 4 5 6 7 File = open (' Test.log ', ' r ') Sizehint = 209715200 # 200M position = 0 lines = file.readlines (sizehint) while not File.tell ()-position < 0:position = File.tell () lines = File.readlines (sizehint)

Each time the ReadLines (sizehint) function is invoked, it returns approximately 200MB of data, which is necessarily the complete row data, and in most cases the number of bytes returned is slightly larger than the value specified by Sizehint (except for the last call to ReadLines ( Sizehint) function. In general, Python automatically adjusts the value of the user-specified sizehint to an integer multiple of the internal cache size.

File in Python is a special type that is used to manipulate external files in a Python program. In Python everything is an object, file is no exception, file has the method and properties of file. Let's look at how to create a file object:

File (name[, mode[, Buffering])

The file () function is used to create a file object that has a name of open () and may be more vivid, which is a built-in function. Take a look at its parameters. Its arguments are passed in string form. Name is the filename of the file.

Mode is the open pattern, and the optional value is R w a U, which represents the pattern of read (default) write-add support for various line breaks. When you open a file in W or a mode, it is created automatically if the file does not exist. In addition, in W mode to open an existing file, the contents of the original file will be emptied, because the first file of the operation of the tag is at the beginning of the file, this time to write operations, will no doubt erase the original content. For historical reasons, line breaks have different patterns in different systems, such as A/N in Unix, and in Windows '/r/n ', which opens the file in U-mode, supports all line-wrapping modes, and says ' R '/n '/r/ N ' can represent a newline, and a tuple is used to store the line breaks used in this file. However, while there are multiple modes of line wrapping, it is common to read in Python instead of using/N. At the back of the pattern character, you can also add the two identities of + B T, which means that you can read and write to the file and open the file in binary mode, text mode (default).

Buffering if 0 means no buffering, if 1 means "row buffering", or a number greater than 1 to indicate the size of the buffer, it should be in bytes.

The file object has its own properties and methods. Let's take a look at the properties of the file.

Closed #标记文件是否已经关闭, rewritten by close ()

Encoding #文件编码

Mode #打开模式

Name #文件名

Newlines #文件中用到的换行模式, is a tuple

Softspace #boolean型, typically 0, is said to be used for print

File read and Write method:

F.read ([size]) #size为读取的长度, in bytes

F.readline ([size])

#读一行, if size is defined, it is possible to return only a portion of a row

F.readlines ([size])

#把文件每一行作为一个list的一个成员, and return to this list. In fact, its internal is through the Loop call ReadLine () to achieve. If the size argument is supplied, the size is the total length of the read content, meaning that it may be read only as part of the file.

F.write (str)

#把str写到文件中, write () does not add a newline character after Str

F.writelines (seq)

#把seq的内容全部写到文件中. This function is also written faithfully and does not add anything behind each line.

Other methods of file:

F.close ()

#关闭文件. Python will automatically close a file after a file is not used, but this feature is not guaranteed, it is best to develop their own habit of shutting down. If a file is turned on after it has been closed it will produce valueerror

F.flush ()

#把缓冲区的内容写入硬盘

F.fileno ()

#返回一个长整型的 "File Label"

F.isatty ()

#文件是否是一个终端设备文件 (in Unix systems)

F.tell ()

#返回文件操作标记的当前位置, with the beginning of the file as the origin

F.next ()

#返回下一行, and the file action tag is shifted to the next line. When you use a file for a statement such as. in file, you call the next () function to iterate through it.

F.seek (Offset[,whence])

#将文件打操作标记移到offset的位置. This offset is generally calculated relative to the beginning of the file, typically a positive number. However, if the whence parameter is provided, the whence can be calculated from scratch for 0, and 1 indicates the current position is the origin calculation. 2 indicates that the origin is computed at the end of the file. Note that if the file is opened in a A or a + mode, the file action tag is automatically returned to the end of the file each time the write operation is performed.

F.truncate ([size])

#把文件裁成规定的大小, the default is the location where the current file action tag is to be trimmed. If the size is larger than a file, depending on the system, you may not change the file, or you can use 0 to make up the file to the appropriate size, or you can add some random content.

I hope this article will help you with your Python programming.

Related Article

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.