Pythonopen () file processing

Source: Internet
Author: User
This article mainly introduces how to use Pythonopen () file processing. For more information, see 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 Traceback (most recent call last) has been closed: File"
 
  
", Line 1, in
  
   
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.