Python Writing Script Common Module OS Basic Usage Detailed Explanation

  • 2021-10-15 10:49:46
  • OfStack

Collected some usage about OS library, sorted out and summarized 1, which is convenient to use


import os

# 系统操作
print(os.sep)       # 获取当前系统的路径分隔符
print(os.name)      # 获取当前使用的工作平台
print(os.getenv('PATH')) # 获取名为 PATH 的环境变量
print(os.getcwd())    # 获取当前的路径
print(os.environ['PATH']) # 可以返回环境相关的信息 不传参时,以字典的方式返回所有环境变量

# 调用系统命令
os.system(command) # 将linux命令传入这里,就可以执行 Execute the command in a subshell. 

# 目录操作 - 增删改查
dir = "/opt/"
listdir_opt = os.listdir(dir) # 返回指定目录下的所有文件何目录名
print(listdir_opt) 
os.mkdir("/opt/os-make/") # 创建1个目录,只创建1个目录文件
os.mknod("/root/python-test.txt") # 创建1个文件
os.rmdir("/opt/ooo/") # 删除1个空目录,若目录中有文件则无法删除
os.remove("/tmp/test.txt") # 用于删除文件,若是目录,则抛出 IsDirectoryError 异常
os.makedirs("/opt/os-make-again/os-make-again-again") # 可以生成多层递归目录,如果目录全部存在,则创建目录失败
os.removedirs() # 从最下级目录开始,逐级删除指定路径,遇到非空目录即停止
os.chdir("/tmp/") # 改变当前目录,到指定目录
os.rename("/opt/ooo/","/opt/AAA/") # 重命名目录名或者文件名。重命名后的文件已存在,则重命名失败。
"""
os.rename()函数的作用是将文件或路径重命名,1般调用格式为os.rename(src, dst),即将src指向的文件或路径重命名为dst指定的名称。

注意,如果指定的目标路径在其他目录下,该函数还可实现文件或路径的“剪切并粘贴”功能。但无论直接原地重命名还是“剪切粘贴”,中间路径都必须要存在,否则就会抛出FileNotFoundError异常。如果目标路径已存在,Windows 下会抛出FileExistsError异常;Linux 下,如果目标路径为空且用户权限允许,则会静默覆盖原路径,否则抛出OSError异常,
和上两个函数1样,该函数也有对应的递归版本os.renames(),能够创建缺失的中间路径。

注意,这两种情况下,如果函数执行成功,都会调用os.removedir()函数来递归删除源路径的最下级目录。
"""

# 判断
if os.path.exists("/root"):
 print("/root 目录存在!")

if os.path.isfile("/root"):
 print("/root 文件存在!")

if os.path.isdir("/etc"):
 print("/etc 目录存在!")

if os.path.isabs("/etc"):
 print("/etc 是绝对路径!")

# path模块
"""
os.path中的函数基本上是纯粹的字符串操作。换句话说,传入该模块函数的参数甚至不需要是1个有效路径,该模块也不会试图访问这个路径,而仅仅是按照“路径”的通用格式对字符串进行处理。
"""
path = "/etc/passwd"
filename = os.path.basename(path) # 返回文件名,如果是目录则为空 实际上是传入路径最后1个分隔符之后的子字符串,也就是说,如果最下级目录之后还有1个分隔符,得到的就会是1个空字符串
filedir = os.path.dirname(path) # 返回的是最后1个分隔符前的整个字符串
filesplit = os.path.split(path) # 将传入路径以最后1个分隔符为界,分成两个字符串,并打包成元组的形式返回
"""
类似的
os.path.splitext("ooo.txt")
('ooo', '.txt')
"""
filesize = os.path.getsize(path) # 获取文件的大小 相当于 ls -l 单位为bytes
fileAbsPath = os.path.abspath(path) # 获取文件的绝对路径
filejoin = os.path.join(path,"test.txt") # 拼接新的路径
"""
如果传入路径中存在1个“绝对路径”格式的字符串,且这个字符串不是函数的第1个参数,那么其他在这个参数之前的所有参数都会被丢弃,余下的参数再进行组合。更准确地说,只有最后1个“绝对路径”及其之后的参数才会体现在返回结果中。

例子如下:

os.path.join("just", "do", "/opt/", "it")
结果: /opt/it
os.path.join("just", "do", "/opt/", "python", "dot", "/root", "com")
结果:/root/com
"""

print(filename+"\n"+filedir+"\n"+str(filesize)+"\n"+fileAbsPath+"\n"+filejoin+"\n")

The usage of the above modules and functions has been explained, and it is not difficult to understand. Here is another function os. walk ()


import os

for item in os.walk("/opt/test-walk/"):
  print(item)

Program output result

('/opt/test-walk/', ['a', 'b', 'c'], [])
('/opt/test-walk/a', [], ['a.txt'])
('/opt/test-walk/b', ['b2'], [])
('/opt/test-walk/b/b2', [], ['b.txt'])
('/opt/test-walk/c', [], [])

Directory structure


[root@open-1 python_scripts]# tree /opt/test-walk/
/opt/test-walk/
 --  a
 The    Off-  a.txt
 --  b
 The    Off-  b2
 The      Off-  b.txt
 Off-  c

4 directories, 2 files

From the above results, we can roughly understand the function of os. walk (): this function needs to pass in a path as a parameter, and the function's function is to walk through the directory tree with the path as the root node, and generate a 3-tuple composed of 3 items (dirpath, dirnames, filenames) for each directory in the tree. Where dirpath is a string indicating the directory path, dirnames is a list of subdirectory names (excluding. and.) under dirpath, and filenames is a list of file names of all non-directories under dirpath. Simply put, it is to list all the directories and files under the target path, and combine the results of tree command to better understand the function.

---------------------------

Create a new directory img in the current directory, which contains multiple files with different file names (X4G5. png)

Change all suffixes ending in. png in the current img directory to. jpg


import random
import string
import os

def gen_code(len=4):
  #  Random generation 4 Bit verification code 
  li = random.sample(string.ascii_letters+string.digits,len)
  return ''.join(li)
def create_file():
  #  Random generation 100 Verification code 
  li = {gen_code() for i in range(100)}
  os.mkdir('img')
  for name in li:
    os.mknod('img/' + name + '.png')

create_file()

def modify_suffix(dirname,old_suffix,new_suffix):
  """
  :param dirname: Directory of operations 
  :param old_suffix:  Previous suffix name 
  :param new_suffix:  New suffix name 
  :return:
  """
  # 1. Judge whether the searched directory exists, and report an error if it does not exist 
  if os.path.exists(dirname):
    # 2. Find out all the old_suffix(.png) Ending file 
    pngfile = [filename for filename in os.listdir(dirname)
          if filename.endswith(old_suffix)]
    # 3. Separate the suffix name from the file name, leaving the file name 
    basefiles = [os.path.splitext(filename)[0]
           for filename in pngfile]
    # 4. Rename file 
    for filename in basefiles:
      oldname = os.path.join(dirname,filename+old_suffix)
      newname = os.path.join(dirname,filename+new_suffix)
      os.rename(oldname,newname)
      print('%s Named %s Success ' %(oldname,newname))
  else:
    print('%s Nonexistent , Can't operate ...' %(dirname))

modify_suffix('redhat','.jpg','.png')

--------------------------

Using the time. time () method, we can calculate the time interval between two time points

But sometimes we want to get the time of a/c/m for the/etc/group file
This information corresponds to the year, month and day
And save it in the file date. txt


import os
import time

time1 = os.path.getctime('/etc/shadow')   # Time stamp time 
print(time1)
tuple_time = time.localtime(time1)
print(tuple_time)
year = tuple_time.tm_year
month = tuple_time.tm_mon
day = tuple_time.tm_mday

with open('date.txt','a') as f:
  f.write('%d %d %d' %(year,month,day))
  f.write('\n')


Related articles: