Python file and input-output summary _python

Source: Internet
Author: User
Tags readline in python

1. Open and close the file (open (), file (), closing ())

There are two built-in functions to get file objects: Open and file. Their usage is exactly the same. The following is just an example of open (). The syntax for getting a file object (open file) is as follows:

Copy Code code as follows:
Fileobj = open (filename,access_mode= ' R ', Buffering=-1)

FileName Needless to say you should also know that you want to open the path of the file.
Access_mode is used to identify the mode in which the file is opened, and the default is R (read only).

Common patterns are shown in the following table:

File mode Explain
R Open in read-only mode
W Open in write mode, empty file when the file is not empty, and create a new file when the file does not exist.
A Append mode, no create
r+,w+,a+ Open in read-write mode, see W,a

There is also a B for binary mode access, but this pattern has no meaning for Linux or Unix systems because they treat all files as binary files, including text files.


The third parameter is not used frequently, identifies the buffer way to access the file, 0 represents does not buffer, 1 represents the slow
Flush one line,-1 represents the default buffering method for the system. Just use the system defaults.

Some examples:

Copy Code code as follows:

>>> f = open ('/etc/passwd ', ' R ')
>>> f1 = open ('/etc/test ', ' W ')

When you are finished using the file, be sure to close the file as follows:

Copy Code code as follows:

>>> F.close ()

2. File read

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

Copy Code code as follows:

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

2.2.file.readlines (Size=-1)

Reads and returns one row (including a line terminator) from a file, or returns the maximum size character

Copy Code code as follows:

>>> F.readline ()
' ogin\n ' #和上面一个例子输出的最后拼起来就是 ' 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 as a list (including the line terminator), if Sizhint>0 returns a row of approximately sizhint bytes (depending on the size of the buffer).

Copy Code code 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:/sbin/shutdown\n ', ' halt:x:7:0:halt:/sbin:/sbin/halt\n ', ' mail:x:8:12 : Mail:/var/spool/mail:/sbin/nologin\n ', ...

Output omitted.

3. File output

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

Copy Code code 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)

Writes a string sequence to a file seq. SEQ is any iteration object that returns a string.

Copy Code code as follows:

>>> f = file ('/root/test.py ', ' + ')
>>> 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 when the file is written, the newline character is not automatically added and must be manually added.

4. File movement

Learn C language classmate, must be fseek () function is not unfamiliar, in Python, Seek () method is fseek () substitution.

Seek (offset,whence=0)
method to move a file cursor to any location in the file. Where offset represents the number of offset bytes that need to be moved, and whence indicates where to start the offset:
0 The representative starts from the beginning of the document,
1 represents starting from the current position,
2 delegates are counted from the end of the file.

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

5. File iterations

In Python, a file is not just an object, but an iterative object! We can use the following iterative approach, easy access and processing of file content, rather than all read out (ReadLines) and then iterate (performance on a lot of bad!) )

Copy Code code as follows:

For Eachline in F:
#dealwith Eachline of F

For example:

Copy Code code as follows:

>>> for Eachline in F:
... print eachline

6.os, Os.path and files

Some of the file-related interfaces are provided in the OS and Os.path, and some commonly used interfaces are described below. Other interfaces can refer to related documents themselves.

Note: The parameters that are passed in the following functions are file names in the form of strings, and file names can be obtained by the file object's Name property.

Function Describe
Os.path.basename () Remove directory path, return filename
Os.path.dirname () Remove filename, return directory path
Os.path.getatime ()
Os.path.getctime ()
Os.path.getmtime ()
Os.path.size ()
Returns the atime,ctime,mtime and size of a file
Os.path.exists () Whether the file or directory exists
Os.path.abs () Specifies whether the 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 the path exists and is a symbolic link

Copy Code code 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

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.