When you want to batch files, using Python to manipulate files or folders is a quick fix. There are several built-in modules in Python that can copy, move, rename, read and write files. The following is a brief introduction to the important functions and methods in the OS and Shutil modules.
1. OS module
Common functions and methods:
A function or method. | instructions | A function or method. | instructions |
---|---|---|---|
os.rename(old, new) | Rename file | os.makedirs(dir) | Creating a Multi-level directory |
os.remove(file) | Delete the file | os.mkdir(dir) | Create a single-level directory |
os.listdir(path) | Lists all files in the directory indicated | os.rmdir(dir) | Deleting an Empty Directory |
os.path.split() | Separate path and file name | os.path.splitext() | Separate files from extensions |
os.path.basename() | Get file name | os.path.exists() | Check whether the file exists |
os.path.isabs() | Check whether it is an absolute path | os.path.isdir() | Check whether it is a directory |
os.path.isfile() | Check whether it is a file | os.path.join() | Combine the path with the filename |
The Shutil module
Common functions and methods:
A function or method. | instructions | A function or method. | instructions |
---|---|---|---|
shutil.copyfile(old, new) | Copy only the contents of the file, no attributes | shutil.copy(old, new) | Contains permission attributes for the file |
shutil.copy2(old, new) | Contains all file attributes | shutil.copytree(old, new) | Copy the entire directory |
shutil.rmtree() | Deleting a Directory (including content) | shutil.move(old, new) | Move directories or files |
Three, file reading and writing
1. Use open (file, ‘mode’) to open a file, or create the file if it doesn’t exist. The second parameter is the file opening mode: r: read mode W: write mode A: read/write mode R + : read/write mode w+ : read/write mode. Overwrite the file if it already exists; If the file does not exist, create it. A + : Read and write. If the file already exists, the file will open in append mode, that is, the cursor will be placed at the end of the file. If the file does not exist, create it.
2. Read and write files. Write (), read(), readline(), and readlines() can be used to read and write files
# Open file
f = open(file, 'a+')
Write characters into files
f.wrire('str')
The length of the file to be read can be specified
f.read()
Size can be specified to read a portion of a line
f.readline()
Read the file and return a list, each line is one element of the list
f.readlines()
# close file
f.close()
Copy the code
To break a line in a file, use the newline character /n