Introduction to Python open () file processing,

Source: Internet
Author: User

Introduction to Python open () file processing,

1. open () syntax

Open (file [, mode [, buffering [, encoding [, errors [, newline [, closefd = True])
Open functions have many parameters, such as file, mode, and encoding.
FileFile Location, which must be enclosed in quotation marks
ModeFile opening mode, see the following 3
BufferingValue Range: 0, 1,> 1. 0 indicates that buffer is disabled (only applicable to binary mode), 1 indicates line buffer (only applicable to text mode),> 1 indicates the initial buffer size;
EncodingIndicates the encoding of the returned data, generally utf8 or gbk;
ErrorsGenerally, strict and ignore are used. When strict is used, an error occurs when the character encoding is incorrect. When ignore is used, the program ignores the Encoding Error, continue to execute the following program.
NewlineThe optional values include None, \ n, \ r, ", '\ r \ n', which is used to differentiate line breaks. However, this parameter is only valid for text mode;
ClosefdThe value is related to the input file parameters. The default value is True. The input file parameter is the file name. When the value is False, the file can only be a file descriptor, what is a file descriptor is a non-negative integer. In a Unix kernel system, a file descriptor is returned when a file is opened.

2. Differences between file () and open () in Python
Both of them can open files and perform operations on files. They also have similar usage and parameters. However, there are essential differences between the two methods,File is a file class., Use file () to open the file, Which is equivalent to constructing a file class, while opening a file with open () isPython built-in functions, We recommend that you use open

3. Basic Values of the mode Parameter

Character Meaning
'R' Open for reading (default)
'W' Open for writing, truncating the file first
'A' Open for writing, appending to the end of the file if it exists
'B' Binary mode
'T' Text mode (default)
'+' Open a disk file for updating (reading and writing)
'U' Universal newline mode (for backwards compatibility; shocould not be used in new code)

R, w, and a are the basic file opening modes, corresponding to the read-only, write-only, and append modes;
B, t, +, and U are used in combination with the preceding file opening mode, binary mode, text mode, read/write mode, and common line breaks,

Common mode value combinations

R or rt default mode. Read the rb binary file w or wt text mode write in text mode. Before the file storage is opened, the wb binary write is cleared, and the file storage is also cleared in a append mode, only the + read/write mode can be written at the end of the file, and the write mode can only be written at the end of the file w + read/write. The difference with a + is to clear the file content r + read/write, the difference with a + is that it can be written to any location of the file.

4. Test
The content of the test file test.txt is as follows:

Hello,Pythonwww.jb51.netThis is a test file

Use a short piece of code to test the visual display of different written files

test = [ "test1\n", "test2\n", "test3\n" ]f = open("test.txt", "a+")try: #f.seek(0) for l in test:  f.write(l)finally: f.close()

Differences between a +, w +, and r + Modes(Test.txt after test)
A + Mode

# cat test.txtHello, Pythonwww.jb51.netThis is a test filetest1test2test3

W + Mode

# cat test.txttest1test2test3

R + Mode
Before writing a file, we add a sentence f. seek (0) is used to locate the write location of the written file (starting with the file) and directly overwrite the number of characters (note \ n is also a character)

# cat test.txttest1test2test3inuxeye.comThis is a test file

Note: When opening a file in r + mode, this file must exist; otherwise, an error is reported, as is the case in 'R' mode.
Other tests

>>> F = open('test.txt ') >>> f. read () # read the entire file. The string is 'hello, Python \ nwww.jb51.net \ nThis is a test file \ n'> f. read () # The pointer is at the end of the file and cannot read the content''
>>> F = open('test.txt ') >>> f. readline () # Read a row at a time. The pointer is 'hello, Python \ n'> f. tell () # length of the modified line 13 >>> f. readline () 'www .jb51.net \ n'> f. tell () 30 >>> f. readline () 'This is a test file \ n'> f. tell () 50 >>> f. readline () ''> f. tell () # The pointer stops at 50 in the last row
>>> F = open('test.txt ') >>> f. readlines () # Read the entire file and display it in the list ['hello, Python \ n', 'www .jb51.net \ n ', 'This is a test file \ n'] >>> f. tell () # The pointer is 50 in the last row
>>> F = open('test.txt ', 'w') # overwrite and create a new file >>> f. write ('hello, Python! ') # If the write content is less than 1024, there will be memory; otherwise, you need to refresh> f. flush () # Write to hard disk >>> f. close () # close the file will automatically refresh> f. write ('hello, Linuxeye ') # write fails, prompting that the File has been disabled Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: I/O operation on closed file

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.