Python file and input/output summary

Source: Internet
Author: User
1. Opening and closing files (open (), file (), close ())

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

The code is as follows:

Fileobj = open (filename,access_mode= ' R ', Buffering=-1)

FileName Needless to say you should also know the path to the file you want to open.
The Access_mode is used to identify the mode in which the file opens, by default R (read-only).

The commonly used patterns are shown in the following table:

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

There's also a B for binary mode access, but this pattern doesn't make sense for Linux or UNIX systems because they treat all files as binaries, including text files.


The third parameter is not often used, the way to identify the buffer to access the file, 0 for non-buffering, 1 for the slow
Punch line, 1 means using system default buffering. As long as you use the system default is good.

Some examples:

The code is as follows:


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

After using the file, be sure to remember to close the file, the operation is as follows:

The code is as follows:


>>> F.close ()

2. File read-in

2.1.file.read (size =-1)
Reads the file contents of size bytes 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:/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 from a file and returns one row (including line terminator), or returns the maximum size characters

The code is 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 that sums approximately sizhint bytes (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:/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)
Writes 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)

Writes a string sequence seq to a file. Seq is an iterative object that returns any 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 when a file is written, a newline character is not automatically added and must be added manually.

4. File movement

Students who have studied C must be familiar with the fseek () function, and in Python, the Seek () method is a substitute for fseek ().

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, whence indicates from which position to start the offset:
0 represents starting from the beginning of the file,
1 represents the beginning of 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, files are more than just an object, but they are an iterative object! We can easily access and process the content of the file using the following iterations, without having to read it all (ReadLines) and iterate (performance is a lot 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

There are some file-related interfaces available in the OS and Os.path, and some commonly used interfaces are described below. Other interfaces can consult the relevant documentation themselves.

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

Function Describe
Os.path.basename () Remove directory path, return file name
Os.path.dirname () Remove file name, 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

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

  • 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.