[TOC]
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:
-
getcwd
Get current directory path
[I have no [email protected] Ceallach_Shaw]$pwd /home/coggle/Ceallach_Shaw [I have no [email protected] Ceallach_Shaw]$vi os_test.py
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 print(os.getcwd())
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 os_test.py /home/coggle/Ceallach_Shaw
-
path.abspath(‘.’)
.
Represents the current path and views the absolute path of the current directoryimport os #print(os.getcwd()) print(os.path.abspath('.'))
Run py file:
[I have no [email protected] Ceallach_Shaw]$python3 os_test.py /home/coggle/Ceallach_Shaw
Supplement:
- “.” 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))
-
listdir(‘.’)
List all files and directories in the current directory
import os l=os.listdir('.') print(l)
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 directory
if os.path.isdir(x)
[x for x in os.listdir('.') if os.path.isdir(x)]
-
mkdir 、rmdir
MKDIR – Create directory, rmdir – delete directory
Create a dir2 directory under the current directory:
import os os.mkdir(os.getcwd()+'/dir2')
Dir2 directory created successfully:
[I have no [email protected] Ceallach_Shaw]$python3 os_test.py [I have no [email protected] Ceallach_Shaw]$ls affairs.txt coggle dir dir2 os_test.py test.py test2.txt
Supplement:
- Removediers, recursively delete directories
- Remove to remove the file
-
rename
File or directory
renameRename directory dir2 to dir3:
import os os.rename('dir2','dir3')
[I have no [email protected] Ceallach_Shaw]$python3 os_test.py [I have no [email protected] Ceallach_Shaw]$ls affairs.txt coggle dir dir3 os_test.py test.py test2.txt
-
path.splitext
Enter the absolute path of the file to get the file extension
import os print(os.path.splitext(os.getcwd()+'os_test.py'))
Output:
(‘/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 file
if os.path.isfile(x)
:l=[x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.py'] print(l)
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.
-
sys.argv
Implement slave program
external
Pass 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:
import sys print(sys.argv)
Output:
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): f=open(filename) while True: line=f.readline() if len(line)==0: break print("wrong! EOF") print(line) if len(sys.argv) < 2: print ('No action specified.') sys.exit() #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''') else: print ('Unknown option.') sys.exit() else: for filename in sys.argv[1:]: readfile(filename)
-
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 print(sys.path)
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.
about
When 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
practice
- 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')]
print(l)
- Print command line parameters
import sys
#The first parameter is the file name, and the externally passed in parameter starts from the second parameter
print(sys.argv[1:])
Reference link:
Welcome to the official account No.Distinct number theory