Python file processing

Source: Internet
Author: User

python经常会操作文件,在磁盘上读写文件的功能都是由操作系统提供的,现代操作系统不允许普通的程序直接操作磁盘,所以,

A read-write file is a request for the operating system to open a file object (often referred to as a file descriptor) and then read the data (read file) from the file object via an interface provided by the operating system, or write the data to the file object (write file)

Python reads a file and uses the built-in function open () to see what a function calls through the syntax below, that is, pass parameters, if there is a keyword specified, then write the specified, if not in the default order to match

Help (Open)
Open (file, mode= ' R ', Buffering=-1, Encoding=none, Errors=none, Newline=none, Closefd=true, Opener=none)
f = open ('/users/michael/test.txt ', ' R ')
f = open ('/users/michael/test.txt ', mode= ' R ', encoding= ' UTF-8 ')

Read () reads the entire contents of the file one time, if the file has 10G, the memory explodes, to be safe, you can repeatedly call the read (size) method, reading the contents of a size byte at most. Other than that
ReadLine () can read a line of content each time, return a string,
ReadLines () reads all the contents one at a time and returns the list by row.
Therefore, you need to decide how to call as needed.

If the file is small, read () One-time reading is the most convenient, if the file size cannot be determined, repeated calls to read (size) insurance, if it is a configuration file, call ReadLines () the most convenient:

For line in F.readlines ():
Print (Line.strip ()) # Erase the end of ' \ n '

The file must be closed after it is used, because the file object consumes the resources of the operating system, and the number of files that the operating system can open at the same time is limited, so you must use F.close () when you have finished reading.

If there is an exception, it throws a ioerror error.

F=open ('/users/michael/notfound.txt ', ' R ')
Traceback (most recent):
File "<stdin>", line 1, in <module>
Filenotfounderror: [Errno 2] No such file or directory: '/users/michael/notfound.txt '

To compensate for an exception, we typically use try finally to handle an unknown exception

Try
f = open ('/path/to/file ', ' R ')
Print (F.read ())
Finally
If f:
F.close ()

所以文件操作一般就是定义一个变量 给变量指向引用对象,open(file_name),然后调用各种操作read文件内容给字符串或者列表对象,最后使用完了记得关闭close()文件鉴于以上复杂的流程,一部到位的好东西with open as file比较好语法:with open() as file:file.read()好搓就是不用自己try finally ,然后系统自己判断异常,

With open (' digui.py ', mode= ' r+ ', encoding= ' Utf-8 ') as MyFile:
Print (Myfile.read ())

IBM Comparison of cattle explanations

Manipulating file objects with the WITH statement
With open (R ' Somefilename ') as Somefile:
For line in Somefile:
Print Line

The WITH statement is used here to ensure that the open file handle has been closed after execution of the WITH statement, regardless of whether an exception occurred during the processing of the file. If you use the traditional try/finally paradigm, use code similar to the following:

Listing 3. Try/finally manipulating File objects

Somefile = open (R ' Somefilename ')
Try
For line in Somefile:
Print Line

Finally
Somefile.close ()
By comparison, using the WITH statement can reduce the amount of coding. There are also modules threading, decimal, etc. that have been added to the context management protocol.

Python file processing

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.