Open () method

The Python open() method opens a file and returns a file object. This function is used during any processing of the file, raising OSError if the file cannot be opened.

Note: When using the open() method, you must ensure that the file object is closed to save the contents of the file. To close the file, you need to call the close() method.

 

The open() method usually takes two arguments: file and mode.

Basic syntax:

open(file,mode='r')

Copy the code

Full syntax:

open(file,mode='r',buffering=1,encoding=None,errors=None,newline=None,closefd=True)

Copy the code

Parameter Description:

File: mandatory, indicating the name of the file in a certain path (relative or absolute path) mode: Specifies the mode in which the file is opened. Buffering: Specifies the mode in which the file is opened. Set bufferencoding: encoding, utF8 Errors: error level newline: distinguish newline closefd: type of the file parameter passed in

Mode means file opening mode. How many modes are there? For reference:

R: Open the file in read-only mode. The pointer to the file will be placed at the beginning of the file. This is the default file opening mode W: opening a file can only be used for writing. If the file exists, open it and edit it from the beginning. The original contents of the file will be cleared. If the file does not exist, a new file is created a: open a file to append content to. If the file already exists, the file pointer will be placed at the end of the file. That is, the new content is written after the existing content. If the file does not exist, create a new file to write to. R +: To open a file for reading and writing, the file pointer will be placed at the beginning of the file a+: If the file already exists, the pointer to the file will be placed at the end of the file. The file will be appended when opened. If the file does not exist, a new file will be created for reading and writing. If the file already exists, open the existing file and edit from the beginning, that is, the original content will be deleted. If the file does not exist, a new file is created b: binary rb: Opens a file in binary format for read-only use. The file pointer will be placed at the beginning of the file. This is the default mode, generally used for non-text files such as pictures, videos etc wb: Opens a file in binary format only for writing. If the file already exists, open the file and edit from the beginning of the file, that is, the original content will be deleted. If the file does not exist, create a new file. Generally used in the text file, such as images, video and other ab: open a file is used to append in binary format, if the file already exists, the end of the file pointer will be placed on file, that is to say, the new content will be wrote the existing content, if the file does not exist, create a new file and write ab + : Open a file in binary format for appending, if the file already exists, the pointer to the file will be placed at the end of the file, if the file does not exist, create a new file for reading and writing

Example 1: Open the file in W mode

f = open('myfile.txt', 'w') f.write('hello,world! ') f.close() ## write 'hello world' to myfile.txt in the current path.Copy the code

Example 2: Open the file in mode A

F =open('myfile.txt','a') f.write('\ngood lucky') f.lose () ## good,lucky!Copy the code

Example 3: If you open the file in W mode, the original content will be overwritten

f = open('myfile.txt', 'w') f.write('welcome! ') f.close() ##Copy the code

Example 4: Read the file in r mode

F = open('myfile.txt', 'r') # open('myfile.txt', 'r') ') f.close() ## output: f.write('\nhello! ') io.UnsupportedOperation: not writableCopy the code

Example 5: Read the file in r+ mode

f = open('myfile.txt', 'r+') f.write('\nhello! R + : Open a file for reading and writing, the file pointer will be placed at the beginning of the file myfile.txt content: 1--------------> here represents a blank line 2hello!Copy the code

Example 6: Write files in W + mode

f = open('myfile.txt', 'w+') f.write('love! ') f.close() ## If the file already exists, open the existing file and edit from the beginning, i.e. the original content will be deleted. If the file does not exist, a new file is created. Myfile.txt contents: love!Copy the code

Read () method

Read everything in the file and move the cursor to the end of the file. It must be in r or R + mode to use read().

Example 7: Write a file in W + mode and read the file in R + mode

f = open('myfile.txt', 'w+') f.write('hello,world! \ngood,lucky!! ') f.close() ## output result: w+ If the file already exists, open the existing file and edit from the beginning, i.e. the original content will be deleted. If the file does not exist, a new file is created. Myfile.txt: Hello,world! good,lucky!!Copy the code
F = open('myfile.txt', 'r+') # print(f.read()) # print(f.read()) good,lucky!!Copy the code

Example 8: Write a file in R + mode and then read the file

F = open('myfile.txt', 'r+') # f = open('myfile.txt', 'r+') # f = open('myfile.txt', 'r+') # f = open('myfile.txt', 'r+') # f = open('myfile.txt', 'r+') # good,lucky!! #myfile.txt reads as follows: 1-----------> empty line 2welcomrld! 3good,lucky!!Copy the code

Readlines () reads the file line by line. Example 9:

F = open('myfile.txt', 'r+') print(f.readline()) print(f.readline()) print(f.readline()) print(f.readline()) # welcomrld! good,lucky!!Copy the code

Readlines () reads the contents of the file one line at a time and stores them in a list. It can read all the contents of each line as an element in the list and returns a list. This list can be used for.. In structure for processing. If an EOF terminator is encountered, a null character is returned.

Example 10:

F = open('myfile.txt', 'r') print(f.readlines())  ['\n', 'welcomrld!\n', 'good,lucky!!'] f = open('myfile.txt', 'r') for i in f.readlines(): I = i. trip () # remove Spaces, such as \ n a newline print (I) # # output content: -- -- -- -- -- -- -- -- -- -- - > empty line welcomrld! good,lucky!!Copy the code

The seek () method

The syntax for seek() is as follows: f.seek(offset,[,whence]) offset– the starting offset, which represents the number of bytes to be moved. If it is negative, the number of bytes to be moved from the bottom whence– This parameter is optional. The default value is 0. Define an argument for offset to indicate where the offset should start. 0 indicates from the beginning of the file. 1 indicates the number starting from the current position. 2 indicates from the end of the file.

If the operation succeeds, the new file location is returned; If the operation fails, -1 is returned

Example 11:

f = open('workfile.txt', 'wb+') print(f word (b'0123456789abcde')) f word (5) print(f word (1)) f word (-3,2) print(f word (1)) # 15 b'5' b'c' workfile. TXT contains the following contents: 0123456789abcdeCopy the code

Example 12:

f = open('myfile.txt', 'r') print('filename is :',f.name) line=f.readline().strip() ## print(' %s' % (line)) f.seek(0, Line =f.readline().strip() print(' the second read is %s' % (line)) Myfile.txt first read data is good, Lucky! The second read is good, Lucky!! Myfile.txt: good,lucky!!Copy the code
## drop f.seek(0, 0)  f = open('myfile.txt', 'r') print('filename is :',f.name) line=f.readline().strip() print(' %s' % (line)) line=f.readline().strip() Print (' %s' % (line)) ## print(' %s' % (line)) The second read is zeroCopy the code

Tell () function

Returns the current location of the file

Reference: www.runoob.com/python/file…

f = open('myfile.txt', 'r+') print('filename is :', Print (' print '%s' % (line)) pos=f.tell() Print ('current position is %d:' % (pos)) f.close() ## Current position is 12: myfile. TXT Filename is: myfile.txt Filename is: myfile.txt G current position is 15: myfile.txt good, Lucky!! gCopy the code

This article is from the SDK community: www.sdk.cn