When copying related files using Python files, we can use the shutil module to copy them. If you are confused about copying Python files, you can use the following methods to learn about the actual operations of Python file replication.
Copy and rename Python files when we want to copy files, we can use the shutil module:
- import shutil
- shutil.copy(myfile, tmpfile)
Last access time and last modification time of the copy:
- shutil.copy2(myfile, tmpfile)
Copy a directory tree:
- shutil.copytree(root_of_tree, destination_dir, True)
The third parameter of the Copytree specifies the processing of symbolic links. True indicates that the symbolic link is retained; False indicates that the physical copy of the Python file replaces the symbolic link. The Python language supports the cross-platform structure of path names: OS. path. the correct delimiter (used in UNIX and Mac OS x operating systems, and in Windows) can be used to join directories and file names. The variable OS. curdir and OS. pardir indicates the current working directory and its parent directory respectively. Like the following UNIX operating system commands
- cp ../../f1.c .
You can use the Python language to provide a cross-platform implementation:
- shutil.copy(os.path.join(os.pardir,os.pardir,’f1.c’), os.curdir)
The rename function in the OS module is usually used to rename a file:
- os.rename(myfile, ’tmp.1’)
Rename myfile to '. This function can also be used to move files in the same file system. Here, we move myfile to Directory d
- os.rename(myfile, os.path.join(d, myfile))
When moving files across file systems, you can use shutil. copy2 to copy Python files and then delete the original copy, as shown below:
- shutil.copy2(myfile, os.path.join(d, myfile))
- os.remove(myfile)
The method for moving files later is the safest.
- copymode(sor,sten)
The above content introduces the practical application solution of Python file replication.