Python file operation read, write, copy plus OS module

Python file operation read, write, copy plus OS module

1. Read

open (path/filename,'rt')------>Return value: stream (stream, pipeline)
container = stream.read()------>Read the content in the pipeline
Insert picture description here
Insert picture description here
2. Write

mode ='w' means write operation, the original content will be cleared each time, and then the current content will be written.
Insert picture description here

Insert picture description here
mode ='a', append mode, do not clear the original content.
Insert picture description here
3. File copy
is a read and a write operation
Insert picture description here

The use of with in combination with open can help us release resources automatically

Insert picture description here
Insert picture description here
4. os module

Insert picture description here

4.1. Get the file directory where the current file is located
Insert picture description here
4.2. Save the previous 1.txt to the directory where the current file is located,
os.path.join() to splice the file name
Insert picture description here
4.3, os.path.split() to split the folder and file name
Insert picture description here
Insert picture description here
4.4. os.path.splitext() Split files and extensions
Insert picture description here
Insert picture description here
4.5. Purpose: Delete the try1 folder. Only when all files in the folder are deleted, the folder can be deleted.
Insert picture description here
4.6. Switch directories, which is equivalent to cd in the terminal :
Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_44994799/article/details/110007500