"No action, no intention" Python foundation - 42. Reading and writing of files in Python

Posted by adzie on Fri, 28 Jan 2022 04:11:57 +0100

(5) File object method (key)

1) Writing method

@1. Grammar

Object object.write('content')

@2. Examples

# 1. Open the file
f = open('test.txt', 'w')

# 2. File writing
f.write('hello world')

# 3. Close the file
# As long as the console displays Process finished with exit code 0
# Prove that the process has ended and the code execution is complete.
f.close()

be careful:

  1. w And a mode:
    If the file does not exist, create the file;
    If the file exists, the w mode is cleared before writing, and the a mode is appended directly to the end.
  2. r mode: if the file does not exist, an error is reported.

@3. Exercise instructions

"""
Test target
1. Impact of access mode on files
2. Access mode pair write()Influence of
3. Can the access mode be omitted
"""

# The access mode parameter can be omitted. If omitted, the access mode is r (read-only)

"""
1.r-Open file in read-only mode: 
1.1 If the file does not exist, an error is reported.
1.2 Write operation is not supported, indicating read-only.
"""
# If the file does not exist, an error is reported
# Result: filenotfounderror: [errno 2] no such file or directory: 'test txt'
f = open('test.txt', 'w')

# The file exists, but write operation is not supported, indicating that it is read-only.
f = open('test.txt', 'r')
# io.UnsupportedOperation: not writable
f.write('aa')
f.close()


"""
2.w-Open file in write mode:
2.1 If the file does not exist, create a new file
2.2 Writing will overwrite the original content
"""
# If the file exists, open the file directly; if the file does not exist, create the file
f = open('1.txt', 'w')
# The written contents directly overwrite the contents of the original file.
f.write('bbb')
f.close()


"""
3.a-Open file in add mode:
3.1 If the file does not exist, create a new file
3.2 Add new contents on the basis of the original contents of the document
"""
# If the file exists, open the file directly; if the file does not exist, create the file
f = open('2.txt', 'a')
# Add new contents on the basis of the original contents of the document
f.write('xyz')
f.close()


"""
4.Run the program once, write()Method can write content to the file multiple times
 Repeated calls in one run write()Write content to the file,
No overrides will be made.
Call twice separately, and the content of the second time will overwrite the content of the first time.

`with...as...`Look at the writing method <6,close>It is explained in
"""
file_name = 'demo.txt'

with open(file_name, 'w', encoding='utf-8') as file_obj:
    file_obj.write('aaa\n')
    file_obj.write('bbb\n')
    file_obj.write('ccc\n')
"""
Document content:
aaa
bbb
ccc
"""


"""
5.write('content')The contents in the method can only be strings,
If a numeric type is entered into the, type conversion is required, otherwise an error will be reported:
TypeError: write() argument must be str, not int
"""
# The code snippet is as follows:
file_obj.write(str(123))

"""
6.write()Method has a return value,
The number of characters written will be returned
"""
# The code snippet is as follows:
r = file_obj.write('It's a nice day today')
print(r)  # 7

2) Reading method

@1.read() method

The read() method is used to read the contents of the file. It will save all the contents as a string and return.

File object.read(num)

Num indicates the length of data to be read from the file (in bytes). If num is not passed in, it means that all data in the file is read.

Example:

"""
If there is a line break in the file content, the bottom layer is\n Line feed will occupy 1 byte,
cause read()The parameters filled in by the method do not match the data read out.
"""
f = open('test.txt', 'r')

# Read no write parameter means to read all;
# print(f.read())
print(f.read(10))

f.close()

@2.readlines() method

The readlines() method can read the contents of the whole file at one time in the form of lines, and returns a list, in which the data of each line (including line breaks) is an element.

f = open('test.txt')
content = f.readlines()

# ['hello world\n', 'abcdefg\n', 'aaa\n', 'bbb\n', 'ccc']
print(content)

# Close file
f.close()

@3.readline() method

The readline() method reads one line at a time.

f = open('test.txt')  # Open in read-only mode

# The first time you call the 'readline()' method, that is, read the first line of the file
content = f.readline()
print(f'First line:{content}')

# Call the 'readline()' method for the second time, that is, read the second line of the file
# and so on
content = f.readline()
print(f'Second line:{content}')

# Close file
f.close()

"""
Output result:
First line: abcde

Line 2: 12345
"""

@4. Read file contents in for loop mode

# Define file name
file_name = 'demo.txt'

# Read the contents of the file circularly, and the variable t is a line of contents in the file
# Traverse once and read one line.
with open(file_name, encoding='utf-8') as file_obj:
    for t in file_obj:
        print(t)

@5. Note:

The above exercises are to open the file in a read-only way and then read the data. Open the file in read-only mode. The cursor is at the beginning of the file by default. We can see the reading results by using read() and other methods.

However, the file can be opened by writing, such as w, a:

  • w: After opening the file, the cursor is at the beginning of the file, but opening the file in W mode will automatically empty the file data, so when we call the read method, we still can't see any data.
  • a: After opening the file, the cursor is at the end of the file content, so when we call the read method, we will still not see any data.

3) seek() method

After opening a file, the position of the file pointer will affect the data read from the file.

The seek() method is used to move the file pointer.

The syntax is as follows:

File object.seek(Offset, Starting position)

Starting position:

  • 0: beginning of file
  • 1: Current location
  • 2: End of file

Example:

"""
Syntax: file objects.seek(Offset, Starting position)
0 Start 1 current 2 end
 Offset:Location to switch to
"""
# Example 1:r open file
# Change the start position of reading data
f = open('test.txt', 'r+')

# 1. Change the start position of reading data, and the beginning is offset by two digits
f.seek(2, 0)

# 2. Put the file pointer at the end of the content
# f.seek(0, 2)

# read file
con = f.read()
print(con)
# Close file
f.close()
"""
Output results
cde
12345
abcde
abcde
"""

# Example 2:a open file
f = open('test.txt', 'a+')

# Put the file pointer at the beginning of the file
# When the parameter is two zeros, it can be abbreviated to one zero
# Indicates no offset, and the starting position is the beginning.
# f.seek(0, 0)
# f.seek(0)

# read file
con = f.read()
print(con)
# Close file
f.close()
"""
Output result:
abcde
12345
abcde
abcde
"""

# Example 3 You can write only the offset,
# The default starting position is 0, starting with
file_obj.seek(55)

# Offset 80 bits backward from the beginning
# file_obj.seek(80,0)
# Offset 70 bits backward from current position
# file_obj.seek(70,1)

# io.UnsupportedOperation: can't do nonzero end-relative seeks
# file_obj.seek(-10,2)

4) tell() method

# The tell() method is used to view the current read position (the position of the cursor)

Examples

with open('demo2.txt','rt' , encoding='utf-8') as file_obj:
    # print(file_obj.read(100))
    # print(file_obj.read(30))

    # seek() can modify the current read position
    # One character in Chinese represents three bytes. If two bytes are intercepted and printed, an error will be reported
    file_obj.seek(9)
    # seek() requires two parameters
    #   The first is the location to switch to
    #   Second calculation position method
    #       Optional values:
    #           0 ab initio, default
    #           1 calculate from current position
    #           2 calculate from the last position

    print(file_obj.read())

    # The tell() method is used to view the current read location
    print('Currently read -->',file_obj.tell())

(6) Shut down

File object.close()

The standard processing format of files in our work is to use with as...

# with ... as statement usage
"""
#with open(file_name) as file_obj and file_obj = open(file_name) is the same
#The return value of open(file_name) is assigned to file_obj
with open(file_name) as file_obj :
    # You can use file directly in the with statement_ Obj to do file operations
    # At this time, this file can only be used in with. Once with ends, the file will be automatically closed ()
    print(file_obj.read())
"""

standard notation

# Determine file name
file_name = 'hello'

try:
    # Open file
    with open(file_name) as file_obj :
        # Processing of documents
        print(file_obj.read())
except FileNotFoundError:
    # The file does not exist for exception handling
    print(f'{file_name} file does not exist~~')

(7) Comprehensive exercise: reading large files

Requirements: read large files

# Determine file name
file_name = 'demo.txt'

try:
    # Call the open() method to open a file, which can be divided into two types
    # One is plain text file (text file written with utf-8 and other codes)
    # One is binary files (pictures, mp3, ppt, etc.)
    # When the open() method opens a file, it is opened in the form of a text file by default,
    # But the default code of the open() method is None,
    # Therefore, when processing text files, you must specify the file code.
    with open(file_name,encoding='utf-8') as file_obj:
        # Read the contents of the file through read()
        # If you call read() directly, it will read out all the contents of the text file,
        # If the file to be read is large, the contents of the file will be loaded into memory at one time,
        # It is easy to cause memory leakage (overflow).
        # Therefore, for large files, do not directly call the read() method to read the file.
        #
        # read() can receive a size as a parameter,
        # This parameter is used to specify the number of characters to be read by calling the read() method once.
        # The default value is - 1, which reads all characters in the file.
        # You can specify a value for size so that the read() method will read the specified number of characters,
        # Each reading starts from the last reading position,
        # If the number of characters is less than size, all remaining characters will be read,
        # If the last of the file has been read, the '' empty string will be returned,
        # content = file_obj.read(-1)
        content = file_obj.read(6)

        """
        Here, you can change to the upper loop method to read the content,
        You can also change to other reading methods.

        # Define a variable to specify the size of each read
        chunk = 100
        # Create a loop to read the contents of the file
        while True:
            # Read the contents of chunk size
            content = file_obj.read(chunk)

            # Check whether the content is read
            # content empty string is false
            if not content:
                # After reading the content, exit the cycle
                break

            # Output content
            # print(content,end='')
        """
except FileNotFoundError :
    print(f'{file_name} This file does not exist!')