Filtering of folders and files

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.
Features of Python to filter files. For example, if we want to list all the 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 .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']

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 Windows will return this string:

The
same is true for part-1\part-2 . When you want to split a path, do not split the string directly, but use the os.path.split() function, so that a path can be split into two parts, the latter part 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 , 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:

Rename the file:

os.rename(‘test.txt’, ‘test.py’)

Delete files:

os.remove('test.py')
But the function for copying 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.

Guess you like

Origin blog.csdn.net/wtt234/article/details/114110054