Article Directory
os
Module and the
shutil
module is the main way to deal with Python file / directory. The os module provides a convenient way to use operating system-related functions, and the shutil module is an advanced file/directory manipulation tool.
Document processing
os
The module provides some convenient functions to use operating system resources, such as reading files in the resource directory, viewing all contents of files in a certain path on the command line, and so on.
Get system type
Compatibility development of the code to adapt to different operating systems can be easily solved by judging the type of operating system.
import os
import sys
print(os.name) # 返回nt代表Windows,posix代表Linux
print(sys.platform) # 更详细信息
Get system environment
When setting environment variables, modules are often called environ
. os.environ
The system environment variables are returned in the form of a dictionary. To obtain specific attribute values, you can use indexes or methods getenv()
:
import os
print(os.environ)
print(os.environ['PATH'])
print(os.getenv('PATH'))
Execute system commands
system()
Shell commands can be executed using the os module method. Normal execution will return 0. The format used is os.system("bash command")
.
When writing in a non-console, system()
only system commands are called but not executed, and the execution results can be read through the popen()
function return file
object.
import os
os.system('ping www.baidu.com')
os.popen('ping www.baidu.com').read()
Manipulate directories and files
One of the most common functions of Python development when using the os module to manipulate directories and files.
method | Description | Example |
os.getcwd() | Get the current directory path | |
os.chdir('target path') | Change the current script directory | |
os.listdir(path) | List all files in the directory | |
os.mkdir(path) | Create a single directory | |
os.makedirs(path) | Create a multi-level directory | |
os.rmdir(path) | Delete single-level empty directories | |
os.removedirs(path) | Delete multi-level directories | |
os.rename("file or directory name", "target name") | Rename directory or file | |
os.path.abspath() | Get absolute path | |
os.path.split(path) | Decompose the path into (folder, file name) If the last character of the path string is \, only the folder part has a value; if there is no \ in the path string, only the file name part has a value; if the path string If there is \ and it is no longer the last, the folder file name has a value. |
|
os.path.join(path1,path2) | Combine paths | |
os.path.dirname(path) | Get the folder part in the path | |
os.path.basename(path) | Get the file name in path | |
os.path.exists(path) | Determine whether the file or folder exists | |
os.path.isfile(path) | Determine whether the path is a file | |
os.path.isdir(path) | Determine whether the path is a directory | |
os.path.getsize(path) | Get file or folder size | |
os.path.getctime(path) | Get file or folder creation time | |
os.path.getatime (path) | Get the last access time of a file or folder | |
os.path.getmtime(path) | Get the last modification time of a file or folder | |
os.sep () | Path separator | |
os.extsep () | Separator between file name and suffix | |
os.pathsep () | Path separator | |
os.linesep () | Line break |
(
Interstitial anti-climbing information) Blogger CSDN address: https://wzlodq.blog.csdn.net/
Advanced processing of files and directories
Compared with the
os
module, theshutil
module is used for advanced processing of files and directories, and provides functions such as supporting file assignment, movement, deletion, compression and decompression.
Copy files
shutil
The main function of the module is the assignment file, and there are about seven implementations:
-
shutil.copyfileobj(file1,file2)
Overwrite copy
Overwrite file2 with the contents of file1, file1 and file2 represent open file objects. -
shutil.copyfile(file1,file2)
Overwriting and copying
is also overwriting, but without opening the file, it is directly overwritten with the file name (the source code is still called copyfileobj). -
shutil.copymode(file1,file2)
Permission copy
Only the file permissions are copied, the content of the file, groups and users are not changed, and no objects are returned. -
shutil.copystart(file1,file2)
Status Copy
Copy all status information of the file, including permissions, groups, users, and time, without returning objects. -
shutil.copy(file1,file2)
Content and permissions copy
Copying the content and permissions of a file is equivalent to executing copyfile first and then copysmode. -
shutil.copy2(file1,file2)
Content and permission copy
Copying the content and all status information of the file is equivalent to executing copyfile first and then copystart. -
shutil.copytree()
Recursive copy
Recursively copy file content and status information
Move files
Use functions shutil.move()
to move files or rename them recursively, and return to the target. If the target is an existing directory, src moves to the current directory; if the target already exists and is not a directory, it may be overwritten.
Read compressed and archive compressed files
Use the function to shutil.make_archive()
create an archive file and return the archived name.
The syntax is as follows:
shutil.make_archive(base_name,format[,root_dir[,base_dir[,verbose[,dry_run[,owner[,group[,logger]]]]]]])
- base_name is the name of the file to be created, including the path
- format means compression format, zip, tar or bztar can be selected
- root_dir is the archive directory
import shutil
path_1 = r'D:\PycharmProjects\Hello'
path_2 = r'D:\PycharmProjects\Hello\shutil-test'
new_path = shutil.make_archive(path_2,'zip',path_1)
print(new_path)
unzip files
Use the function to shutil.unpack_archive(filename[,extract_dir[,format]])
analyze the unpacking.
- filename is the full path of the archive
- extract_dir is the name of the target directory to extract the archive
- format is the format of the decompressed file
import shutil
import os
shutil.unpack_archive('D:\PycharmProjects\Hello\shutil-test.zip','D:\\testdir')
print(os.listdir('D:\\testdir'))
summary
It should be noted that in different operating systems, path separators are different, and need to be considered when processing files. It can also be used os.sep()
to replace the file separator, because of the program exception caused by the operating system. In addition, when handling files, you often need to pay attention to file permissions, as well as the difference between files and folders, and the use of recursion.
Python series blog is continuously updated
The original is not easy, please
donot reprint (this is not wealthy visits make it worse)
blogger homepage: https://wzlodq.blog.csdn.net/WeChat
public account : If the article is helpful to you, remember to click three links ❤唔仄lo咚锵