Operating files and directories of python IO programming

Python study notes, special records, share with you, I hope it will be helpful to everyone.

Manipulate 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 these directory and file operations 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 os module of Python can also directly call the interface functions provided by the operating system.

Open the Python interactive command line, let's take a look at how to use the basic functions of the os module:

import os
print os.name

operation result:

posix

Process finished with exit code 0

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:

print os.uname()

operation result:

('Darwin', 'FBY-is-MBP', '16.8.0', 'Darwin Kernel Version 16.8.0: Mon Mar 11 20:40:32 PDT 2019; root:xnu-2782.20.48~5/RELEASE_X86_64', 'x86_64')

Process finished with exit code 0

Note that the uname() function is not provided on Windows, that is to say, 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:

print os.environ

operation result:

{'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', ...}

Process finished with exit code 0

To get the value of an environment variable, you can call os.environ.get('key'):

print os.environ.get('PATH')
print os.environ.get('x', 'default')

operation result:

/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/usr/local/mysql/bin
default

Process finished with exit code 0

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:

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

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

operation result:

'/Users/michael/testdir', 'file.txt'

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

print os.path.splitext('/path/to/file.txt')

operation result:

'/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:

# 对文件重命名:
print os.rename('test.txt', 'test.py')
# 删掉文件:
print 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, which can be seen as a supplement to the os module.

Finally, look at how to use the 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:

print [x for x in os.listdir('.') if os.path.isdir(x)]

operation result:

['.lein', '.local', '.m2', '.npm', '.ssh', '.Trash', '.vim', 'Applications', 'Desktop', ...]

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

print [x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.py']

operation result:

['apis.py', 'config.py', 'models.py', 'pymonitor.py', 'test_db.py', 'urls.py', 'wsgiapp.py']

Guess you like

Origin blog.csdn.net/qq_36478920/article/details/99584536