Python fragmentation knowledge (3): basic file operations

Source: Internet
Author: User

I. Overview

Python built-in functionsOpenIs used to open a file on the disk and return a file object. All subsequent operations on the file are performed using this "handle". The file methods can be divided: input, output, file movement, and others.

1. open the file

OpenThe method can receive three parameters: file name, mode, and buffer parameters. Only the first parameter, file name, is required; the other two are optional. If not specified, the file is opened in text format.

1 f=open('demo.txt ', 'w') 2 print f. name 3 print f. demo4 5 name attribute; file name 6 demo attribute; mode in which the file is opened

2. close the file

Opening a file consumes system resources and depends on the file mode. Other programs may not be able to access them. This is the key to closing the file once the operation is complete.

1 f. close () 2 f. closed # Output True, indicating that the file is closed. 3 4 # If the file is closed, all methods that can open the file are unavailable. 5 f. seek () 6 f. tell () 7 f. read () 8 f. close ()

 

2. Understanding how to read files
For example, we can read the file all. py.

 1 ''' 2 Created on 2013-3-7 3  4 @author: Administrator 5 ''' 6 def info(object, spacing=10, collapse=1):    7     """Print methods and doc strings. 8      9     Takes module, class, list, dictionary, or string."""10     methodList = [method for method in dir(object) if callable(getattr(object, method))]11     processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)12     print "\n".join(["%s %s" %13                       (method.ljust(spacing),14                        processFunc(str(getattr(object, method).__doc__)))15                      for method in methodList])16 17 if __name__ == "__main__":                 18     print info.__doc__

The operation code for the above files is as follows:

1 # coding = UTF-8 2''' 3 Created on 2013-3-7 4 5 @ author: Administrator 6''' 7 f = open ("all. py "," rb ") # open receives three parameters: file name, mode, and buffer parameter 8 print f. tell () # Open the current location of the file. Because we haven't done anything to the file, the current location is 0, indicating the start of the file 9 f. seek () # The seek method of the file object, which indicates moving to another position in the open file 10 print f. tell () 11 tagData = f. read (10) # The read method reads a specified number of bytes from the open file, and returns a string containing 12 print tagData13 print f. tell () # The tell method confirms that the current position has been moved 14 ------------- 15 and the output is as follows:
0
10
ed on 2013
20

Understanding: this series of operations seems to be when we first open the notepad, the cursor immediately stays at the top left corner (0) of the notepad, which corresponds to the tell () after the open at the beginning (). If we want to move the cursor position, for example, from the beginning to 10 characters, we can use seek (10, 0), and then in tell (), we can find that the cursor has been positioned to 10, then, read 10 characters from 10th. We can use read (10)

Iii. File writing:

The Python open method is used to open a file. The first parameter is the file location and file name, and the second parameter is the read/write mode.

1. write: w (write) | a (append)
2. Read: r
3. binary: Write: wb; read: rb

1. Store and restore Python objects in files 2. Use the Python pickle module to directly store Python objects in files and restore them to the content as needed. 3 4 5 # coding = UTF-8 6 ''' 7 Created on 2013-3-7 8 9 @ author: administrator10''' 11 file = open ("pickle.txt", "w ") 12 import pickle13 dict = {"name": "BeginMan", "age": "22"} 14 pickle. dump (dict, file) 15 file. close () 16 17 test = open ("pickle.txt", "r") 18 print pickle. load (test) 19 test. close ()

IV. I/O Exception Handling

The following operations on files can cause an IOError:

1. The file does not exist. An exception occurs when you use open ('...', 'R') to open a file that does not exist.

2. If seek (n) is used when the file length is smaller than the specified length (for example, n), an exception is thrown.

3. The file is damaged. If the disk is damaged, the read () operation causes an exception.

 

We need to handle the exception as follows:

 1 try: 2     f=open('d.txt','r') 3     try: 4         f.seek(100,2) 5         fshow=f.read(1000) 6     finally: 7         f.close() 8  9     except IOError:10     pass

Step 1: try to process when opening the file
Step 2: Based on step 1, try to process files during operations
Step 3: Remember to close the file after the operation is complete and complete it in finally
Last step: handle T IOError: ...... handle the exception

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.