Python file input and output

1. Open the file

1.1 open() method

The Python open() method is used to open a file and return a file object. This function needs to be used in the process of processing the file. If the file cannot be opened, OSError will be thrown.

Note: When using the open() method, you must ensure that the file object is closed, that is, call the close() method.

The common form of the open() function is to receive two parameters: the file name (file) and the mode (mode).

open(file, mode='r')

The full syntax format is:

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

Parameter Description:

  • file: required, file path (relative or absolute path)
  • mode: optional, file opening mode
  • buffering: set buffering, use memory instead of hard disk, make the program faster

For parameter explanation, see: Python3 File(file) method .

1.2 File mode

model describe
r Open the file read-only. The file pointer will be placed at the beginning of the file. This is the default mode.
w Open a file for writing only. If the file already exists, the file will be opened and edited from the beginning, ie the original content will be deleted. If the file does not exist, create a new file.
a Open a file for appending. If the file already exists, the file pointer will be placed at the end of the file. That is, the new content will be written after the existing content. If the file does not exist, a new file is created for writing.
b binary mode.
+ Open a file for update (readable and writable).

For parameter explanation, see: Python3 File(file) method .

2. Basic file method

2.1 Reading and writing

File objects are created using the open function, and data is written and read using the write and read methods.

f = open('somefile.txt','w')
f.write('Hello,')
f.write('wordl!')
f.close()

f = open('somefile.txt','r')
print(f.read(5))
print(f.read())
f.close()

output:

Hello
,wordl!

Note: Newline writing needs to be added after the character\n

f = open('somefile.txt','w')
f.write('01234567890123456789\n')
f.write('Hello,world!\n')
f.close()

f = open('somefile.txt','r')
print(f.readline())
f.close()

2.2 Random access

The seek() method is used to move the file reading pointer to the specified position. The seek() method syntax is as follows:

fileObject.seek(offset[, whence])

parameter

  • offset – the starting offset, which represents the number of bytes that need to be shifted
  • whence: optional, default value is 0. Give the offset parameter a definition, indicating where to start the offset; 0 means counting from the beginning of the file, 1 means counting from the current position, and 2 means counting from the end of the file.
f = open('somefile.txt','w')
f.write('01234567890123456789')
f.seek(5)
f.write('Hello,world!')
f.close()

f = open('somefile.txt','r')
print(f.read())
f.close()

output:

01234Hello,world!789

The tell() method returns the current position of the file, which is the current position of the file pointer. The tell() method syntax is as follows:

fileObject.tell()
f = open('somefile.txt','r')
print(f.read(3))
print(f.read(2))
print(f.tell())
f.close()

output:

012
34
5

2.3 Reading lines

The readline() method is used to read an entire line from a file, including "\n" characters. If a non-negative argument is specified, returns the number of bytes of the specified size, including the "\n" characters. The readline() method syntax is as follows:

fileObject.readline(size)

Parameter
size – the number of bytes to read from the file.
Return Value
Returns the bytes read from the string.

line = f.readline()

The readlines() method is used to read all lines (until the end character EOF) and return a list, which can be processed by Python's for...in... structure. Returns an empty string if the terminator EOF is encountered. The syntax of the readlines() method is as follows:

fileObject.readlines( );

parameter
None.
Return Value
Returns a list containing all rows.

2.5 Iterating over file content

2.5.1 Byte processing

method 1:

def process(string):
    print('Proecss: ',string)

f = open('somefile.txt','w')
f.write('First line\n')
f.write('Second line\n')
f.write('Third line\n')
f.close()

f = open('somefile.txt','r')
char = f.read(1)
while char:
    process(char)
    char = f.read(1)
f.close()

Method 2:

f = open('somefile.txt','r')
while True:
    char = f.read(1)
    if not char:
        break
    process(char)
f.close()

2.5.2 Processing by row

f = open('somefile.txt','r')
while True:
    line = f.readline()
    if not line:
        break
    process(line)
f.close()

2.5.3 Read everything

If the file is not very large, you can use read or readlines to read it all. When the file is very large, you can use while and readline instead.

f = open('somefile.txt','r')
for char in f.read():
    process(char)
f.close()
f = open('somefile.txt','r')
for line in f.readlines():
    process(line)
f.close()

2.5.4 Iterating with fileinput

The fileinput module contains functions for opening files.

import fileinput
for line in fileinput.input('somefile.txt'):
    process(line)

output:

Proecss:  First line
Proecss:  Second line
Proecss:  Third line

2.5.5 File iterators

Super cool method, it seems that the readlines method does not need to exist.
method 1:

f = open('somefile.txt','r')
for line in f:
    process(line)
f.close()

Method 2:

for line in open('somefile.txt','r'):
    process(line)

Although there should be a file object to close the open file, as long as there is no write operation to the file, it is also possible not to close it.

Method 3:

lines = list(open('somefile.txt','r'))
print(lines)

Converts a file iterator to a list of strings, to achieve the same effect as using readlines.

2.6 Example from ChatGPT

Example 1:

	filename = 'test.txt'
    fid = open(filename)

    if fid == -1:
        print(f"The file '{filename}' does not exist.")
        return

    bulletinas = []
    i = 0
    while not fid.eof():
        current_line = fid.readline()
        print(current_line)

Example 2:

	filename = 'test.txt'
    bulletinas = []
    with open(filename) as f:
        for current_line in f:
        print(current_line)        

Reference: ChatGPT https://openai.com/

3. Binary file reading and writing

Python reads and writes the binary data of the file is much more complex than the C/C++ language. The main difference is the conversion between bytes type and other basic data types (such as int/float).
For details, see:
[1] Python processes binary files (.bin)
[2] Python reads and writes binary data of files

Guess you like

Origin blog.csdn.net/wokaowokaowokao12345/article/details/128801327