Python file and input/output summary

Source: Internet
Author: User
Python is an object-oriented programming language, and files are also a type. The following is a brief introduction to help you 1. open and close files (open (), file (), close ())

Two built-in functions can be used to obtain file objects: open and file. Their usage is the same. The following uses open () as an example. Syntax:

The code is as follows:

FileObj = open (filename, access_mode = 'R', buffering =-1)

Not to mention filename, you should also know the path of the file to be opened.
Access_mode is used to identify the file opening mode. the default value is r (read-only ).

The common modes are shown in the following table:

File mode Explanation
R Open in read-only mode
W Open the file in write mode. if the file is not empty, clear the file. if the file does not exist, create a new file.
A Append mode. if not, create an append mode.
R +, w +, a + Open in read/write mode. For more information, see w,.

In addition, B indicates binary access, but this mode does not make sense for Linux or unix systems because they regard all files as binary files, including text files.


The third parameter is not frequently used. it indicates the buffer mode for accessing the file. 0 indicates no buffer, and 1 indicates slow
-1 indicates that the system uses the default buffer mode. You only need to use the system default.

Some examples:

The code is as follows:


>>> F = open ('/etc/passwd', 'r ')
>>> F1 = open ('/etc/test', 'w ')

After using the file, remember to close the file as follows:

The code is as follows:


>>> F. close ()

2. file reading

2.1.file.read (size =-1)
Reads the size of the file starting from the current file cursor. If size =-1, all remaining bytes are read.

The code is as follows:


>>> F = open ('/etc/passwd ')
>>> F. read (100)
'Root: x: 0: 0: root:/bin/bash \ nbin: x: 1: 1: bin:/sbin/nologin \ ndaemon: x: 2: 2: daemon:/sbin/nol'

2.2.file.readlines (size =-1)

Read from the file and return a line (including the row Terminator), or return a maximum of size characters

The code is as follows:


>>> F. readline ()
'Ogin \ n' # The final combination of the above example output is 'nologin', because the cursor is behind l.
>>> F. readline (1)
'A'

2.3.file.readlines (sizhint = 0)
Reads all the rows of the file and returns the result as a list (including the row Terminator). if sizhint> 0, the total number of rows in the sizhint byte is returned (determined by the buffer size ).

The code is as follows:


F. readlines ()
['DM: x: 3: 4: adm:/var/adm:/sbin/nologin \ n', 'LP: x: 4: 7: lp: /var/spool/lpd:/sbin/nologin \ n', 'sync: x: 5: 0: sync:/sbin:/bin/sync \ n', 'shutdown: x: 6: 0: shutdown:/sbin/shutdown \ n', 'halt: x: 7: 0: halt:/sbin: /sbin/halt \ n', 'mail: x: 8: 12: mail:/var/spool/mail:/sbin/nologin \ n ',......

The output is omitted.

3. file output

3.1.file.write (str)
Write the specified string to the file.

The code is as follows:


>>> F = file ('/root/test. py', 'W + ')
>>> F. write ("print 'Hello, world '")
>>> F. read ()
''
>>> F. close ()
>>> File ('/root/test. py', 'r'). read ()
"Print 'Hello, world '"

3.2.file.write (seq)

Write string sequence seq to the file. Seq is any iteratable object that returns a string.

The code is as follows:


>>> F = file ('/root/test. py', 'A + ')
>>> Codelst = ['\ n', 'import OS \ n', "OS. popen ('Ls'). read () \ n"]
>>> F. writelines (codelst)
>>> F. close ()
>>> File ('/root/test. py', 'r'). read ()
"Print 'Hello, world' \ nimport OS \ nos. popen ('Ls'). read () \ n"

Note that the line break is not automatically added when the file is written, and must be manually added.

4. file movement

If you have studied C language, you must be familiar with the fseek () function. in Python, the seek () method is a substitute for fseek.

Seek (offset, whence = 0)
You can move the file cursor to any position of the file. Here, offset indicates the number of offset bytes to be moved, and whence indicates the starting position of the offset:
0 indicates starting from the beginning of the file,
1 indicates starting from the current position,
2 indicates counting from the end of the file.

So how do we know where the current file cursor is? Don't worry, here is a tell () method that can return the cursor position of the current file.

5. file iteration

In Python, a file is not only an object, but also an iteratable object! We can use the following iteration method to easily access and process file content, without having to read all the data (readlines) before iteration (performance is much worse !)

The code is as follows:


For eachline in f:
# Dealwith eachline of f

For example:

The code is as follows:


>>> For eachline in f:
... Print eachline

6. OS, OS. path, and files

OS and OS. path provide file-related interfaces. The following describes some common interfaces. You can view related documents for other interfaces.

Note: the parameters passed in by the following functions are all file names in string format. the file name can be obtained by the name attribute of the file object.

Function Description
OS. path. basename () Remove the directory path and return the file name.
OS. path. dirname () Remove the file name and return the directory path.
OS. path. getatime ()
OS. path. getctime ()
OS. path. getmtime ()
OS. path. size ()
Returns the atime, ctime, mtime, and size of the file.
OS. path. exists () Whether the file or directory exists
OS. path. abs () Whether the specified path is an absolute path
OS. path. isdir () Whether the path exists and is a directory
OS. path. isfile () Whether the path exists and is a file.
OS. path. islink () Specifies whether a path exists and is a symbolic link

The code is as follows:


>>> Import OS. path
>>> F = open ('/root/test. py', 'r ')
>>> OS. path. basename (f. name)
'Test. py'
>>> F. name
'/Root/test. py'
>>> OS. path. getsize (f. name)
52
>>> OS. path. isabs (f. name)
True
>>> OS. path. isdir (f. name)
False

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.