SoFunction
Updated on 2024-11-16

Python using the open function on the file in detail

Use the open function in python to work with files.

()

python opens a file using the open() function, which returns a pointer to the file. The function commonly takes the following three arguments.

1.1 Parameter 1

Path + name of the target file. It is better to use the raw string r "path" to prevent any escape characters from affecting the actual path.

1.2 Parameter 2

The way to manipulate the file mode='mode'. mode= can be omitted. The following is a detailed description of the mode in which the file is manipulated.

(1)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 open default mode. If the file does not exist, an error will be reported.

(2)rb

Opens a file in binary read-only mode. The file pointer will be placed at the beginning of the file. Note that you cannot use encoding in this way, or you will get an error.

The same content is opened using the normal way and the binary way.

fp = open(r"E:\",'r',encoding='utf-8')
content = ()
print(content)

Output: Come on, do a good job!

fp = open(r"E:\",'rb')
content = ()
print(content)

Output: b'\xe5\x8a\xa0\xe6\xb2\xb9\xef\xbc\x8c\xe5\xa5\xbd\xe5\xa5\xbd\xe5\xe5\xbd\xe5\xb9\xb2\xef\xbc\x81'

(3)r+

Opens a file as read or write. The file pointer will be placed at the beginning of the file. Writing directly will overwrite the beginning of the file.

Original content:

Come on, do well! Don't give up.

fp = open(r"E:\",'r+',encoding='utf-8')
("Have fun.")
()
fp = open(r"E:\", 'r', encoding='utf-8')
content = ()
print(content)
()

Post-implementation:

Have fun and do well! Don't give up.

(4)rb+

Opens a file as a binary read/write. The file pointer will be placed at the beginning of the file.

(5)w

Opens a file with Write. If the file already exists, it is overwritten. If the file does not exist, creates a new file.

(6)wb

Opens a file as a binary write. If the file already exists, it is overwritten. If the file does not exist, creates a new file.
(7)w+

Opens a file as read/write. If the file already exists, it is overwritten. If the file does not exist, a new file is created.

Original content:

Have fun and do well! Don't give up.

fp = open(r"E:\",'w+',encoding='utf-8')
("Be serious.")
()
fp = open(r"E:\", 'r', encoding='utf-8')
content = ()
print(content)
()

Directly overwrite all original content after execution:

Be serious.

(8)wb+

Opens a file in binary read/write format. If the file already exists, it is overwritten. If the file does not exist, a new file is created.

(9)a

Opens a file as an append. If the file already exists, the file pointer will be placed at the end of the file. That is, the new content will be appended to the existing content. If the file does not exist, a new file is created that can be written to. Note that it is not possible to read, reading will result in an error.

(10)a+

Opens a file as read or write. If the file already exists, the file pointer will be placed at the end of the file. That is, the new content will be appended to the existing content. If the file does not exist, a new file is created that can be used for reading and writing.

Original content:

Be serious.

fp = open(r"E:\",'a+',encoding='utf-8')
("You're just a little bit closer to success.")
()
fp = open(r"E:\", 'r', encoding='utf-8')
content = ()
print(content)
()

Post-implementation additions:

If you're serious, you're closer to success.

At this point, the pointer is placed at the end of the file, direct reading will have no content, you need to move the pointer (seek) to the head of the file:

with open(r"E:\",'a+',encoding='utf-8') as fp:
    (0,0)
    content = ()
    print(content)

(11)ab+

Opens a file as a binary read/write. If the file already exists, the file pointer will be placed at the end of the file. That is, the new content will be appended to the existing content. If the file does not exist, a new file is created that can be read or written to.

1.3 Parameter 3

The way of encoding, commonly used utf-8, gbk and so on. Such as: encoding='utf-8'

This parameter does not need to be filled in if it is a binary method, and will report an error if it is filled in.

open() as

This is an upgraded use of open(), where the file is automatically closed at the end of the control block, and there is no need to display a call to close() to close the file. This method is much easier to use, so it is recommended.

with open(r"E:\",'r',encoding='utf-8') as fp:
    content = ()

Commonly used methods for functions

3.1 Reading

File contents:

If you're serious, you're closer to success.
Ahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh!
fffffffffff

(1)read()

Reads the contents of an entire file at once, putting the entire file into a string. Use the read(size) method to return the first size characters in the file:

content = ()

Output:

If you're serious, you're closer to success.
Ahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh!
fffffffffff

(2)readline()

Reads one line at a time.

content = ()

Output:

If you're serious, you're closer to success.

(3)readlines()

Read the entire contents of the file at once into an iterator for us to traverse (it's easier to read into a list for use)

content = ()

OUTPUTS;

[‘If you're serious, you're closer to success.\n’, ‘Ahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh!\n’, ‘fffffffffff’]

3.2 Write

(1)write()

The argument to () must be a string, which is what you want to write to the file.

(2)writelines()

The argument to () can be either a list or a string.

3.3 Getting file read/write types

The () method returns True if the file is writable, otherwise it returns False.

The () method returns True if the file is readable, otherwise it returns False.

For example: a file opened as w, () returns False, () returns True.

3.4 Pointer movement

seek

(offset, [start position])

Three values for the start position: 0 at the beginning of the file, 1 at the current position, and 2 at the end of the file.

For an example see (10) in 1.3 a+

3.5 Current Pointer Position

tell() returns an integer indicating the location of the current file pointer (that is, the number of bytes to the header).

If it is utf-8 encoding, then one Chinese character occupies three bytes and one English character occupies one byte. If it is gbk encoding, then one Chinese character occupies two bytes and one English character occupies one byte.

with open(r"E:\",'a+',encoding='utf-8') as fp:
    content = ()
    print(content)

Printing: 30

3.6 truncate

truncate(size) method is used to truncate a file. If the optional parameter size is specified, the file is truncated to size characters. If size is not specified, the file is truncated from the current position; after truncation, all characters after size are deleted.

summarize

to this article on the use of python open function to file processing article is introduced to this, more related to the use of python open function please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!