If we want to manipulate files and directories, we can enter various commands provided by the operating system under the command line to complete. such as dir
, and cp
other orders.
What if you want to perform these directories and files in a python program? In fact, the commands provided by the operating system simply invoke the interface functions provided by the operating system, and Python's built-in os
modules can invoke the interface functions provided by the operating system directly.
To open the Python interactive command line, let's look at how to use os
the basic functionality of the module:
>>> import os>>> os.name # OS type 'posix'
If yes posix
, the system is Linux
, Unix
or Mac OS X
, if it is, the nt
Windows
system.
To get detailed system information, you can call the uname()
function:
>>> os.uname () posix.uname_result (sysname='Darwin', nodename=' michaelmacpro.local', release='14.3.0', version=' Darwin Kernel Version 14.3.0:mon Mar 11:59:05 PDT; root:xnu-2782.20.48~5/release_x86_64 ', machine='x86_64')
Note that uname()
functions are not available on Windows, that os
is, some functions of the module are related to the operating system.
Environment variables
The environment variables defined in the operating system are all stored in os.environ
this variable and can be viewed directly:
>>>Os.environenviron ({'Versioner_python_prefer_32_bit':'No','term_program_version':'326','LOGNAME':'Michael','USER':'Michael','PATH':'/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/x11/bin:/usr/local/mysql/bin', ...}) To get the value of an environment variable, you can call Os.environ.Get('Key'):>>> Os.environ.Get('PATH')'/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/x11/bin:/usr/local/mysql/bin'>>> Os.environ.Get('x','default')'default'
Manipulating Files and directories
os
It is important to note that part of the function for manipulating files and directories is placed in the module and part of the os.path
module. viewing, creating, and deleting directories can be called:
# View the absolute path of the current directory:>>> Os.path.abspath ('.')'/users/michael'# Create a new directory under a directory and first represent the full path to the new directory:>>> Os.path.join ('/users/michael','TestDir')'/users/michael/testdir'# Then create a directory:>>> Os.mkdir ('/users/michael/testdir') # Delete a directory:>>> Os.rmdir ('/users/michael/testdir')
To synthesize two paths, do not spell the string directly, but pass the os.path.join()
function so that the path delimiter of the different operating systems can be handled correctly. Under Linux/unix/mac, os.path.join()
return such a string:
part-1/part-2
and Windows will return such a string:
part-1\part-2
同样的道理,要拆分路径时,也不要直接去拆字符串,而要通过os.path.split()
函数,这样可以把一个路径拆分为两部分,后一部分总是最后级别的目录或文件名:
>>> os.path.split ('/users/michael/testdir/file.txt') (' /users/michael/testdir ' ' file.txt ')
os.path.splitext()
You can get the file extension directly, and many times it is very convenient:
>>> os.path.splitext ('/path/to/file.txt') ('/path/to/ File'.txt')
These functions of merging and splitting paths do not require directories and files to be real, they operate only on strings.
The file operation uses the following function. Assume that there is a file in the current directory test.txt
:
# Renaming files:>>> os.rename ('test.txt'test.py') ) # Erase files:>>> os.remove ('test.py')
But the function of copying files os
does not exist in the module! The reason is that the copy file is not a system call provided by the operating system. Theoretically, we can copy files by reading and writing files from the previous section, just to write a lot more code.
Fortunately, the shutil
copyfile()
functions provided by the module, you can also shutil
find a lot of practical functions in the module, they can be seen as a complement to os
the module.
Finally, see how to filter files using Python's features. For example, we want to list all the directories in the current directory, just one line of code:
>>> [x forXinchOs.listdir ('.')ifOs.path.isdir (x)] ['. Lein','. Local','. M2','. NPM','. SSH','. Trash','. Vim','Applications','Desktop', ...]
To list all the .py
files, just one line of code:
>>> [x forXinchOs.listdir ('.')ifOs.path.isfile (x) and Os.path.splitext (x) [1]=='. PY']['apis.py','config.py','models.py','pymonitor.py','test_db.py','urls.py','wsgiapp.py']
Isn't it very concise?
Summary
Python's os
modules encapsulate the operating system's directory and file operations, and note that some of these functions are in os
modules, some in os.path
modules.
34 Manipulating files and directories