Earlier, we learned the basic concepts of python modules, how to install third-party modules, and learned to write our own modules and packages. Click here to review:


Python module introduction and installation (offline, non-administrator)

How to write your own modules and packages


A classmate asked a question: How to copy, delete, and rename files in python?


A classmate knew os.system ( ) and replied:

os.system ( ' cp av bv' )

os.system ( ' rm bv ' )

os.system ( ' mv av bv' )


What if it's a windows system?


A classmate familiar with DOS commands replied:

os.system ( ' copy av bv ' )

os.system ( ' del bv ' )

os.system ( ' rename av bv ' )

Another classmate found a "universal" method and said that Unix-like gadgets can be installed on Windows, and then continue to use the Linux method.

In fact, python has already considered the issue of system compatibility for us. There is the following description on python's official website:

" Runs anywhere, including Mac OS X , Windows , Linux , and Unix , with unofficial builds also available for Android and iOS .

Therefore, before we start a more in-depth study, it is necessary for us to learn the basic way of dealing with the operating system ( os ), files ( sys ), and shells ( shutil ). The three modules/packages, os, sys, and shutil, are provided with python installation, which can basically cover our needs.

Research what functions os, sys, shutil provide

Let's first use dir() to see which functions are provided by these three modules/packages, and then pick some commonly used functions to introduce. After importing the os module, use dir(os) to see which functions are provided by os, as follows (the commonly used ones are marked in blue):

>>> import os
>>> dir(os)

[..., 'abc', 'abort', 'access', 'altsep', ' chdir ', ' chmod ', ' chown ', 'chroot', 'close', 'closerange', 'confstr', ' confstr_names', ' cpu_count ', 'ctermid', ' curdir ', 'defpath', 'device_encoding', 'devnull', 'dup', 'dup2', ' environ ',
'environb', 'errno', 'error' , 'execl', 'execle', 'execlp', 'execlpe',
'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fchdir', 'fchmod',
'fchown', 'fdatasync', 'fdopen', 'fork', 'forkpty', 'fpathconf',
'fsdecode', 'fsencode', 'fspath', 'fstat', 'fstatvfs', 'fsync',
'ftruncate', 'fwalk' , 'get_blocking', 'get_exec_path',
'get_inheritable', 'get_terminal_size', 'getcwd ', 'getcwdb', 'getegid', ' getenv ',
'getenvb', 'geteuid', 'getgid', 'getgrouplist', 'getgroups',
'getloadavg', 'getlogin', 'getpgid', 'getpgrp' , 'getpid', 'getppid',
'getpriority', 'getresgid', 'getresuid', 'getsid', 'getuid', 'getxattr',
'initgroups', 'isatty', ' kill ', 'killpg', ' lchown', 'linesep', 'link', ' listdir ', 'listxattr', 'lockf', 'lseek', 'lstat', 'major', 'makedev', ' makedirs ', 'minor', 'mkdir ', 'mkfifo', 'mknod', ' name ', 'nice', 'open', 'openpty', 'pardir', ' path ', 'pathconf', 'pathconf_names', 'pathsep', 'pipe' , 'pipe2', ' popen', 'posix_fadvise', 'posix_fallocate', 'pread', 'putenv', 'pwrite', 'read', 'readlink', 'readv', ' remove ', ' removedirs ', 'removexattr', ' rename ', ' renames ', ' replace ', ' rmdir ', ' scandir ',
'sched_get_priority_max', 'sched_get_priority_min',
'sched_getaffinity', 'sched_getparam', 'sched_getscheduler', 'sched_param',
'sched_rr_get_interval', 'sched_setaffinity',
'sched_setparam' ', 'sched_setscheduler', 'sched_yield', 'sendfile', ' sep ',
'set_blocking', 'set_inheritable', 'setegid', 'seteuid', 'setgid',
'setgroups', 'setpgid', 'setpgrp', 'setpriority', 'setregid',
'setresgid', 'setresuid', 'setreuid', 'setsid', 'setuid', 'setxattr',
'spawnl', 'spawnle ', 'spawnlp', 'spawnlpe', 'spawnv', 'spawnve',
'spawnvp', 'spawnvpe', 'st', 'stat', 'stat_float_times', 'stat_result',
'statvfs', 'statvfs_result', 'strerror', 'supports_bytes_environ',
'supports_dir_fd', 'supports_effective_ids', 'supports_fd',
'supports_follow_symlinks', ' symlink ', 'sync', 'sys', 'sysconf', 'sysconf_names', ' system ', 'tcgetpgrp', 'tcsetpgrp', 'terminal_size', 'times', 'times_result', 'truncate', 'ttyname', 'umask', ' uname ', 'uname_result', ' unlink ', ' unsetenv ', 'urandom ', 'utime', 'wait', 'wait3', 'wait4', 'waitid', 'waitid_result', 'waitpid', 'walk', 'write', 'writev']

sys and shutil are left to the students to do their own experiments.

Arrange the research results as follows

We have organized the function names that look familiar as follows.

os.name

os.getcwd

os.listdir

os.remove

os.makedirs

os.mkdir

os.rmdir

os.chdir

os.rename

os.system

os.sep

os.linesep

os.environ

os.path.abspath

os.path.dirname

os.path.basename

os.path.isfile

os.path.isdir

os.stat

os.path.split

os.path.join

os.popen

os.path.exists

os.symlink

sys.argv

sys.exit

sys.path

sys.platform

sys.stdin

sys.stdout

sys.stderr

shutil.chown

shutil.copy

shutil.copy2

shutil.copytree

shutil.disk_usage

shutil.errno

shutil.make_archive

shutil.which

What's the use of just listing a function name? Why is there no usage introduction? There are so many functions that I don't want to and don't really want to write a full usage description and usage example for each function. Let me introduce how to check the help documentation.

Understand the purpose and usage of each function

For example, if you want to see the usage of os.getcwd and os.popen, you can do the following in terminal:

[billc@bclinux ~]$ python3   enter python interactive mode
Python 3.6.2 (default, Aug 20 2017, 10:04:14)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux
Type " help", "copyright", "credits" or "license" for more information.
>>> import os
>>> import sys
>>> help(os.getcwd)     
Use help() to see usage

Help on built-in function getcwd in module posix:
getcwd()
    Return a unicode string representing the current working directory.

>>> help(os.popen      ) View usage with help()

Help on function popen in module os:
popen(cmd, mode='r', buffering=-1)
    # Supply os.popen()

>>> os.getcwd() still don't understand? Do an experiment '/home/billc'     prints the current path        

>>> os.popen('ls')     do another experiment
<os._wrap_close object at 0x7f75fcda1208> 
returns an object

>>> os.popen('ls').readlines()  continue to experiment
['Desktop\n', 'Documents\n', 'Downloads\n', 'Music\n', 'Pictures\n', ' Public\n', 'Videos\n']       outputs the execution result of the ls command


Still don't know what to do?

  • python book

  • Baidu, bing, google (if you are abroad, or you have a VPN/VPS)

  • Zhihu, blog

  • Find some open source code references on github

  • classmates, colleagues, friends

  • WeChat group

Of course, you can also read the "Application of Python in ASIC" series of articles on the public account Ex ASIC .


Analysis of difficult problems

os.mkdir and os.makedirs


mkdir creates a single directory, while makedirs creates a list of directories, similar to the shell command make -p.


os.mkdir( 'a' )

os.makedirs( 'a/b/c' )


os.path.curdir, os.path.abspath, os.path.dirname, os.path.basename


curdir is a property, not a function, returns a string  '.'

abspath returns the full path.

The input arguments to dirname and basename are full paths, basename returns the filename, and dirname returns the path preceding the filename.


os.path.abspath( 'file.txt' )     # /home/xxx/dir/file.txt

os.path.dirname( '/home/xxx/dir/file.txt' )      # /home/xxx/dir

os.path.baseame( '/home/xxx/dir/file.txt' )     # file.txt

os.path.dirname( '../../file.txt' )   # ../../

Therefore, dirname and basename do not determine whether the file or path actually exists, but only process the provided string.


os.path.isdir, os.path.isfile, os.path.islink


These functions are not only for string processing, but an error will be reported when the file or directory does not exist. From the name, you can see their function, determine whether it is a file, directory, soft link, and return True and False.


os.path.split, os.path.splitext, os.path.join


Split is to separate directories and files, splitt is to separate file names from suffix names, and join combines directories and files into paths with /.


os.path.split( '/home/xxx/dir/file.txt' )   # ['/home/xxx/dir', 'file.txt']

os.path.splitext( 'file.txt' )   # ['file', '.txt']


os.path.getsize, os.path.getatime, os.path.getctime, os.path.getmtime


os.path.getsize gets the size of the file.

os.path.getatime The last access time, which can be created, modified, read, etc.

os.path.getctime The last change time, which can be modified, changed permissions, changed owner, etc.

os.path.getmtime Last modification time, creation, modification, etc.

More information about the file can be obtained with os.stat().



Write a useful script/code

For example, when we simulate, we need to create a simulation directory according to the name of the testcase.

The specific matters are as follows:

  1. Get testcase name from command line

  2. Confirm the project root directory and get the relative path of the current directory

  3. Use the find command to get the category of the testcase

  4. If the category does not exist, create a new category directory and generate a Makefile

  5. enter the category directory

  6. If the testcase directory does not exist, create a new one, and create a soft link and Makefile for the simulation script

  7. After completion, print success message

Reference script:

picture

picture

picture

    More python articles    

Why Python

Getting to know the Python language

Preparation before writing Python

my first python program

Python Data Types (1): Introduction

Python data types (2): numbers

Python data type (3): string

Python data types (4): list List and tuple Tuple

Python data type (5): dictionary Dict

Conditions and Loops in Python

Python functions (1): basic concepts

Python function (2): scope

Python function (3): parameter passing

Python functions (4): recursive functions and anonymous functions, attributes and annotations of functions

Python Developers Survey 2017 Results

picture

We all know what editor to choose for writing Python. (It turns out that there are so few people using Emacs)

picture

Copy the link to the browser to view the full "Investigation Report" (the survey report on the Python official website) :

https://www.jetbrains.com/research/python-developers-survey-2017/

commercial time

picture

Welcome to Ex ASIC

picture

Share experiences and methods in digital integrated circuit design

Sharing makes work smoother

picture