File operations in python

File operations in python

1,What is a file
    Files are operations provided to users/A mechanism for applications to access hard disks

2,Why use files
    Permanently save data

3,How does the code manipulate files
	keyword open()
    Three steps:
    	1.Use keywords open Open file
        2.Use other methods to manipulate files
        3.Close file

File path

Relative path and absolute path
 The so-called relative path is relative to your target file location.

Relative path:

Absolute path:

The combination of letters and slashes in the path has a special meaning. How to cancel it?
Prefix the path string with an r
r'D:\pycharm \ test \ a.txt '

If you open a file, you need these three parameters:


Open (file path, read / write mode, character encoding)
File path and read / write mode are required
Character encoding is optional (some modes require encoding)
res = open('a.txt', 'r', encoding='utf8')
The process of file running is like this.

Open the file. The application program initiates a system call open(...) to the operating system. The operating system opens the file, corresponds to a piece of hard disk space, and returns a file object, which is assigned to a variable res

print(res.read()) calls the read / write method under the file object, which will be converted by the operating system to read / write the hard disk

res.close() sends a request to the operating system to close files and reclaim system resources

Open a file that contains two resources:
The variable res of the application and the file opened by the operating system. When a file is operated, all the resources related to the file must be recycled. The recycling method is as follows:

1. res.close() # reclaims file resources opened by the operating system
2. del res # reclaims application level variables
del res must occur after res.close(). Otherwise, the files opened by the operating system cannot be closed and resources will be occupied for nothing.
The automatic garbage collection mechanism of Python determines that we don't need to consider del res, which requires us to remember res.close() after operating the file, but most people still forget res.close involuntarily. Considering this, python provides the key word with

1. After executing the sub code block, with will automatically execute f.close()

with open('a.txt','w') as res:
pass

Among them, pass is only to complete the grammatical structure, which has no practical significance.

2. You can use with to open multiple files at the same time, separated by commas

with open('a.txt','r') as read_res,open('b.txt','w') as write_res:
data = read_res.read()
write_res.write(data)

Specifies the character encoding of the operation text file

The operating system operating system opens the file. If the text file is opened, it will involve the character encoding problem. If no code is specified for open, then the default encoding of the open text file is obviously the operation system says that the operation system will open the file with its default encoding, gbk under windows, utf-8 under F, and open.

This uses the knowledge of character coding mentioned in the last lesson: if you want to ensure that there is no random code, you should open the file in what way you save it.

f = open('a.txt','r',encoding='utf-8')

Controls the mode of file read and write operations

Just remember three ①. 'r' (default): read only ②. 'w': write only ③. 'a': write only
r Read only mode (can only be viewed and cannot be changed)

# Path does not exist: direct error reporting
 with open(r'b.txt', 'r', encoding='utf8') as f:
     pass
# Path exists
 with open(r'a.txt', 'r', encoding='utf8') as f:
     print(f.read())  # Read all the contents of the file
     f.write('123')  # Write file content

w Write only mode (write only, no view)

# Path does not exist: automatically created
# with open(r'b.txt', 'w', encoding='utf8') as f:
#     pass

# Path exists: 1. The file content will be emptied first. 2. Write operation will be performed again
with open(r'a.txt', 'w', encoding='utf8') as f:
    # f.read()
    f.write('hello world!\n')
    f.write('hello world!\n')
    f.write('hello world!\n')

Before operation
function

After running, it is directly cleared and re written to hello world!

a append mode only (additional content)

#Path does not exist: automatically created
# a mode: append mode only
with open(r'a.txt','a',encoding='utf8') as f:
 pass
 Path exists:The file is not emptied and content is added at the end of the file
with open(r'a.txt', 'a', encoding='utf8') as f:
 f.write('\n Today is Thursday. I'm going to have a holiday soon. I'm so happy!')


After five runs
Small summary
The RWA read-write mode we use can only operate on text files

File operation method

# File operation method
# 1. Reading series
with open(r'a.txt', 'r', encoding='utf8') as f:
    # print(f.read())  # Read all the contents of the file at once
    # print(f.readline())  # Read only one line of file at a time
    # print(f.readlines())  # Read all the contents of the file and organize them into a list. Each element is the content of each line of the file
    # print(f.readable())  # Judge whether the current file has the ability to read


# 2. Write series
with open(r'a.txt','w',encoding='utf8') as f:
    # f.write('Overcome all difficulties, Ollie!')  # Write text content to file
    # f.write(123)  # The content written must be of string type
    # f.writelines(['jason','kevin','tony'])  # You can write all the string elements in the list
    # print(f.writable())  # True
    # print(f.readable())  # False
    f.flush()  # Directly brush the file data in memory to the hard disk, which is equivalent to ctrl+s

File optimization operation

with open(r'a.txt', 'r', encoding='utf8') as f:
    # print(f.read())  # Read all the contents of the file at once
    # print(f.read())  # Read all the contents of the file at once
    # print(f.read())  # Read all the contents of the file at once
    """
    1.After one-time reading, the cursor stays at the end of the file and cannot read the content again
    2.This method may cause memory overflow when reading large files
        The strategy to solve the above problem is to read the file contents line by line
    """
    # for line in f:  # The file variable name f supports the for loop, which is equivalent to reading the file content line by line
    #     line
    '''In the future, when the content of multi line files is involved, it is generally adopted for Cyclic reading'''

Posted by fishdishdesign on Thu, 11 Nov 2021 15:26:44 -0800