Python learning-manipulating files and directories

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, cp and other commands.

What if you want to perform operations on these directories and files in a Python program? In fact, the commands provided by the operating system simply call the interface functions provided by the operating system, and the built-in Python os module can also directly call the interface functions provided by the operating system.

Open the Python interactive command line, let's see how to use the basic functions of the os module:

>>> import os
>>> os.name # 操作系统类型
'posix'

If it is posix, it means that the system is Linux, Unix or Mac OS X; if it is nt, it is a 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 23 11:59:05 PDT 2015; root:xnu-2782.20.48~5/RELEASE_X86_64', machine='x86_64')

Note that the uname() function is not provided on Windows, that is, some functions of the os module are related to the operating system.

Environment variable

The environment variables defined in the operating system are all stored in the variable os.environ, which can be viewed directly:

>>> os.environ
environ({
    
    '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'

Manipulate files and directories

Part of the functions for manipulating files and directories are placed in the os module, and part of the functions are placed in the os.path module. Pay attention to this point. View, create and delete directories can be called like this:

# 查看当前目录的绝对路径:
>>> os.path.abspath('.')
'/Users/michael'
# 在某个目录下创建一个新目录,首先把新目录的完整路径表示出来:
>>> os.path.join('/Users/michael', 'testdir')
'/Users/michael/testdir'
# 然后创建一个目录:
>>> os.mkdir('/Users/michael/testdir')
# 删掉一个目录:
>>> os.rmdir('/Users/michael/testdir')

When combining two paths into one, do not directly spell strings, but use the os.path.join() function , so that the path separators of different operating systems can be correctly processed. Under Linux/Unix/Mac, os.path.join() returns a string like this:

part-1/part-2

And under Windows will return such a string:

part-1\part-2

In the same way, when you want to split a path, don't split the string directly, but use the os.path.split() function , so that a path can be split into two parts, and the latter part is always the last-level directory or file name:

>>> os.path.split('/Users/michael/testdir/file.txt')
('/Users/michael/testdir', 'file.txt')

os.path.splitext() can directly let you get the file extension , which is very convenient in many cases:

>>> os.path.splitext('/path/to/file.txt')
('/path/to/file', '.txt')

These functions for merging and splitting paths do not require directories and files to exist, they only operate on strings.

File operations use the following functions. Assume that there is a test.txt file in the current directory:

# 对文件重命名:
>>> os.rename('test.txt', 'test.py')
# 删掉文件:
>>> os.remove('test.py')

But the function to copy files does not exist in the os module! The reason is that copying files is not a system call provided by the operating system. In theory, we can complete file copying by reading and writing files in the previous section, but we need to write a lot of code.

Fortunately, the shutil module provides the copyfile() function. You can also find many useful functions in the shutil module. They can be seen as a supplement to the os module.

Finally, let's see how to use the features of Python to filter files. For example, if we want to list all directories in the current directory, we only need one line of code:

>>>[x for x in os.listdir('.') if os.path.isdir(x)]
>['.lein', '.local', '.m2', '.npm', '.ssh', '.Trash', '.vim', 'Applications', 'Desktop', ...]

To list all the .py files, only one line of code is required:

>>> [x for x in os.listdir('.') if os.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']

summary

Python's os module encapsulates the directory and file operations of the operating system. Note that some of these functions are in the os module, and some are in the os.path module.

Exercise

  1. Use the os module to write a program that can realize dir -l output.
  2. Write a program that can search for files with the specified character string in the current directory and all subdirectories of the current directory, and print out the relative path.

Guess you like

Origin blog.csdn.net/qq_44787943/article/details/112574083