Fundamentals of Linux (III)



Create py files in the directory and run them

OS module

In Python, there is a built-in library OS, which is a system interface library, operating system interfaces. When processing data and running scripts in Linux system, files and directories are often operated, so the OS library plays this role. The operation of files and directories with fixed logic can be written in the form of scripts.

Here are some common methods:

  1. getcwd

    Get current directory path

     [I have no [email protected] Ceallach_Shaw]$pwd
     [I have no [email protected] Ceallach_Shaw]$vi

    Create a new py file, introduce the OS module, and print the current path using the getcwd method. Note: VI is used here, so the method to exit saving is to exit the insert mode by ESC, switch to the command line mode, enter WQ, and press enter to save. (the use of VI in the following article will not be repeated. Students who forget will read the previous articleFundamentals of Linux (I)

    import os

    On the command line, run the PY file, and the printed path is consistent with the current path.

     [I have no [email protected] Ceallach_Shaw]$python3 
  2. path.abspath(‘.’)

    .Represents the current path and views the absolute path of the current directory

    import os

    Run py file:

    [I have no [email protected] Ceallach_Shaw]$python3 


    • “.” Indicates the current directory, or “. /”;
    • “..” Indicates the upper level directory or “.. /”;
    • “~” represents the user’s Host Directory;
    • “/” is at the top of the Linux file system tree structure. We call it the root of the Linux file system. It is the entry of the Linux file system (refer to the directory structure diagram in the previous article)Fundamentals of Linux (I)
  3. listdir(‘.’)

    List all files and directories in the current directory

    import os

    Fundamentals of Linux (III)

    If you only need to list all directories under the current directory (files are not required), add a condition after the for loop to judge whether it is a directoryif os.path.isdir(x)

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

    Fundamentals of Linux (III)

  4. mkdir 、rmdir

    MKDIR – Create directory, rmdir – delete directory

    Create a dir2 directory under the current directory:

    import os

    Dir2 directory created successfully:

    [I have no [email protected] Ceallach_Shaw]$python3 
    [I have no [email protected] Ceallach_Shaw]$ls
    affairs.txt  coggle  dir  dir2  test2.txt


    • Removediers, recursively delete directories
    • Remove to remove the file
  5. rename

    File or directoryrename

    Rename directory dir2 to dir3:

    import os
    [I have no [email protected] Ceallach_Shaw]$python3 
    [I have no [email protected] Ceallach_Shaw]$ls
    affairs.txt  coggle  dir  dir3  test2.txt
  6. path.splitext

    Enter the absolute path of the file to get the file extension

    import os


    (‘/home/coggle/Ceallach_Shawos_test’, ‘.py’)

    List all in the current directory Py file, you need to add conditions to judge whether it is a fileif os.path.isfile(x):

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

    Fundamentals of Linux (III)

Sys module

Sys module is mainly responsible forInteract with Python interpreter, the module provides a series of functions and variables for controlling the python running environment.

  1. sys.argv

    Implement slave programexternalPass parameters to the program, in short, sys Argv [] is a bridge to get parameters from outside the program. It returns a parameter list. The first element is the program itself, followed by externally given parameters.

    Here is the help information for printing Python:

    Fundamentals of Linux (III)

    import sys

    Fundamentals of Linux (III)

    It can be seen that the first parameter of the output is the file name, and the subsequent parameters are the externally passed in parameters.

    We often see that on the command line, enter — help, – version and other parameters to print out relevant information. sys. Argv is used to pass external parameter values to the target method / function.

    Let’s look at another related example in the book. About the implementation of — help, – version parameter:

    import sys
    def readfile(filename):
       while True:
          if len(line)==0:
                print("wrong! EOF")
    if len(sys.argv) < 2:
       print ('No action specified.')
    #Intercept from the second parameter (the first parameter passed in externally), starting with -- and starting from the third character of this parameter
    if sys.argv[1].startswith('--'):
       option = sys.argv[1][2:]
       #If -- is followed by version, version 1.2 is output
       if option == 'version':
          print ('Version 1.2')
       elif option == 'help':
          print ('''\
    This program prints files to the standard output.
    Any number of files can be specified.
    Options include:
    --version : Prints the version number
    --help    : Display this help''')
          print ('Unknown option.')
       for filename in sys.argv[1:]:
  2. sys.path

    Gets a collection of strings for the specified module search path.

    When we import a module: import XXX, by default, the python parser will search and print it in the order of current directory, installed built-in modules and third-party modules. The search path is stored in the path of sys module:

    import sys

    Fundamentals of Linux (III)

    Now there is a very common situation that you write py files and put them in another directory. If the PY file in the current directory needs to reference the methods in the written py file, you need to add the directory where the PY script is stored to sys Path.

    aboutWhen the module to be referenced and the script file to be executed are not in the same directory, you can add a path as follows:

    import sys  
    sys. path. Append ('address of module to be referenced ')  
    # sys. path. append(..)   #  This represents adding a directory above the current path


  1. Use the OS module to print all files starting with m in the / usr / bin / path
import os 

#First switch to the / usr / bin / directory
c = os.chdir('/usr/bin/')

# path. The isfile method determines whether it is a file, and startswitch determines the initial letter M at the beginning of the string
l = [x for x in os.listdir(c) 
            if os.path.isfile(x) and x.startswith('m')]


Fundamentals of Linux (III)

  1. Print command line parameters
import sys

#The first parameter is the file name, and the externally passed in parameter starts from the second parameter

Fundamentals of Linux (III)

Reference link:


Welcome to the official account No.Distinct number theory
Fundamentals of Linux (III)

Recommended Today

You have to know about JVM garbage collection

catalogue 1、 Four citation methods1.1 strong reference1.2 soft reference1.3 weak reference1.4 phantom reference 2、 How to judge whether the object is garbage2.1 reference counting method2.2 root accessibility analysis 3、 Garbage collection algorithm3.1 mark sweep3.2 mark compact3.3 mark copy 4、 Garbage collector4.1 classification and characteristics4.1.1 serial4.1.2 throughput priority4.1.3 priority of response time4.2 serial garbage collector details […]