01_os module commonly used operations

01_os module commonly used operations

Commonly used operations of os module

# -*- coding: utf-8 -*-
# @Time    : 2023/5/28 15:11
# @Author  : 脚本非挂
# @File    : os模块常用操作.py
# @Description : 公众号:脚本非挂
import os


def os_get_cwd() -> str:
    """
    获取当前文件所在的文件夹
    @return: 当前文件所在的文件夹
    """
    return os.getcwd()


def os_path_exists(file_path: str) -> bool:
    """
    判断文件是否存在
    @param file_path: 文件的路径
    @return: bool
    """
    return os.path.exists(file_path)


def os_listdir(path: str) -> list:
    """
    返回文件夹下的所有文件名
    @param path: 文件夹路径
    @return: file_names
    """
    return os.listdir(path)


def os_path_join(path, *paths) -> str:
    """
    拼接文件路径和文件
    @param path: 文件路径或文件
    @param paths: 文件路径或文件
    @return: str
    """
    return os.path.join(path, *paths)


def os_get_size(file_path: str, num=2) -> str:
    """
    获取文件的大小,
    @param file_path:文件的路径
    @param num:保留的小数位
    @return:
    """
    file_size = os.path.getsize(file_path)
    if 0 <= file_size < 1024 * 1024:
        file_size = f"{
      
      round(file_size / 1024, num)} Kb"
        print(file_size)

    if 1024 * 1024 <= file_size < 1024 * 1024 * 1024:
        file_size = f"{
      
      round(file_size / (1024 * 1024), num)} Mb"
        print(file_size)

    if 1024 * 1024 * 1024 <= file_size < 1024 * 1024 * 1024 * 1024:
        file_size = f"{
      
      round(file_size / (1024 * 1024 * 1024), num)} Gb"
        print(file_size)

    return file_size


def os_remove(file_path: str) -> None:
    """
    删除文件,建议使用文件的绝对路径
    @param file_path: 文件的路径
    @return: None
    """
    return os.remove(file_path)


def os_rename(old_name, new_name) -> None:
    """
    重命名文件,建议使用文件的绝对路径
    @param old_name:旧的文件名
    @param new_name:新的文件名
    @return:None
    """
    return os.rename(old_name, new_name)


def os_walk(path):
    """
    生成目录树下的所有文件名
    @param path:文件夹的路径
    @return:文件的绝对路径列表,输出文件夹的绝对路径列表
    """
    file_list = []
    dir_list = []
    for root, dirs, files in os.walk(path):
        for name in files:
            file_path = os.path.join(root, name)
            file_list.append(file_path)
            # print(file_path)    # 输出文件的绝对路径
        for name in dirs:
            dir_path = os.path.join(root, name)
            dir_list.append(dir_path)
            # print(dir_path)     # 输出文件夹的绝对路径
    return file_list, dir_list


def os_system(cmd: str) -> int:
    """
    执行CMD命令,只返回执行结果,0:pass, 1:Fail
    @param cmd: 命令集
    @return: 0 or 1
    """
    return os.system(cmd)


def os_popen(cmd: str):
    """
    执行CMD命令,返回执行结果
    @param cmd: 命令集
    @return: 
    """
    return os.popen(cmd).read()


def os_change_dir(path) -> None:
    """
    切换工作目录,
    @param path: 目录
    @return:
    """
    return os.chdir(path)

Python OS file/directory method command set

serial number method name effect
1 os.access(path, mode) Check permission mode
2 os.chdir(path) Change current working directory
3 os.chflags(path, flags) Set the path's tag to a numeric tag.
4 os.chmod(path, mode) Change permissions
5 os.chown(path, uid, gid) Change file owner
6 os.chroot(path) Change the root directory of the current process
7 os.close(fd) Close file descriptor fd
8 os.closerange(fd_low, fd_high) Close all file descriptors from fd_low (inclusive) to fd_high (exclusive), errors will be ignored
9 os.dup(fd) copy file descriptor fd
10 os.dup2(fd, fd2) Copy a file descriptor fd to another fd2
11 os.fchdir(fd) Change the current working directory through a file descriptor
12 os.fchmod(fd, mode) Change the access permissions of a file. The file is specified by the parameter fd. The parameter mode is the file access permissions under Unix.
13 os.fchown(fd, uid, gid) Modify the ownership of a file. This function modifies the user ID and user group ID of a file specified by the file descriptor fd.
14 os.fdatasync(fd) Forces the file specified by file descriptor fd to be written to disk, but does not force the file's status information to be updated.
15 os.fdopen(fd[, mode[, bufsize]]) Create a file object through file descriptor fd and return this file object
16 os.fpathconf(fd, name) Returns system configuration information for an open file. name is the value of the system configuration being retrieved, which may be a string that defines a system value. These names are specified in many standards (POSIX.1, Unix 95, Unix 98, and others).
17 os.fstat(fd) Returns the status of file descriptor fd, like stat().
18 os.fstatvfs(fd) Returns file system information for the file containing file descriptor fd, like statvfs()
19 os.fsync(fd) Force the file with file descriptor fd to be written to the hard disk.
20 os.ftruncate(fd, length) Crop the file corresponding to file descriptor fd, so it cannot exceed the maximum file size.
21 os.getcwd() Return to current working directory
22 os.getcwdu() Returns a Unicode object of the current working directory
23 os.isatty(fd) If the file descriptor fd is open and connected to a tty (-like) device, returns true, otherwise False.
24 os.lchflags(path, flags) Set the path flag to a numeric flag, similar to chflags(), but without soft links
25 os.lchmod(path, mode) Modify connection file permissions
26 os.lchown(path, uid, gid) Change the file owner, similar to chown, but does not follow the link.
27 os.link(src, dst) Create a hard link named parameter dst pointing to parameter src
28 os.listdir(path) Returns a list of the names of files or folders contained in the folder specified by path.
29 os.lseek(fd, pos, how) Set the current position of the file descriptor fd to pos, how to modify it: SEEK_SET or 0 sets the pos calculated from the beginning of the file; SEEK_CUR or 1 calculates from the current position; os.SEEK_END or 2 starts from the end of the file. In Unix, Windows Moderately effective
30 os.lstat(path) Like stat(), but without soft links
31 os.major(device) Extract the device major number from the original device number (using the st_dev or st_rdev field in stat).
32 os.makedev(major, minor) Use the major and minor device numbers to form an original device number
33 os.makedirs(path[, mode]) Recursive folder creation function. Like mkdir(), but all intermediate-level folders created need to contain subfolders.
34 os.minor(device) 从原始的设备号中提取设备minor号码 (使用stat中的st_dev或者st_rdev field )。
35 os.mkdir(path[, mode]) 以数字mode的mode创建一个名为path的文件夹.默认的 mode 是 0777 (八进制)。
36 os.mkfifo(path[, mode]) 创建命名管道,mode 为数字,默认为 0666 (八进制)
37 os.mknod(filename[, mode=0600, device]) 创建一个名为filename文件系统节点(文件,设备特别文件或者命名pipe)。
38 os.open(file, flags[, mode]) 打开一个文件,并且设置需要的打开选项,mode参数是可选的
39 os.openpty() 打开一个新的伪终端对。返回 pty 和 tty的文件描述符。
40 os.pathconf(path, name) 返回相关文件的系统配置信息。
41 os.pipe() 创建一个管道. 返回一对文件描述符(r, w) 分别为读和写
42 os.popen(command[, mode[, bufsize]]) 从一个 command 打开一个管道
43 os.read(fd, n) 从文件描述符 fd 中读取最多 n 个字节,返回包含读取字节的字符串,文件描述符 fd对应文件已达到结尾, 返回一个空字符串。
44 os.readlink(path) 返回软链接所指向的文件
45 os.remove(path) 删除路径为path的文件。如果path 是一个文件夹,将抛出OSError; 查看下面的rmdir()删除一个 directory。
46 os.removedirs(path) 递归删除目录。
47 os.rename(src, dst) 重命名文件或目录,从 src 到 dst
48 os.renames(old, new) 递归地对目录进行更名,也可以对文件进行更名。
49 os.rmdir(path) 删除path指定的空目录,如果目录非空,则抛出一个OSError异常。
50 os.stat(path) 获取path指定的路径的信息,功能等同于C API中的stat()系统调用。
51 os.stat_float_times([newvalue]) 决定stat_result是否以float对象显示时间戳
52 os.statvfs(path) 获取指定路径的文件系统统计信息
53 os.symlink(src, dst) 创建一个软链接
54 os.tcgetpgrp(fd) 返回与终端fd(一个由os.open()返回的打开的文件描述符)关联的进程组
55 os.tcsetpgrp(fd, pg) 设置与终端fd(一个由os.open()返回的打开的文件描述符)关联的进程组为pg。
56 os.tempnam([dir[, prefix]]) 返回唯一的路径名用于创建临时文件。
57 os.tmpfile() 返回一个打开的模式为(w+b)的文件对象 .这文件对象没有文件夹入口,没有文件描述符,将会自动删除。
58 os.tmpnam() 为创建一个临时文件返回一个唯一的路径
59 os.ttyname(fd) 返回一个字符串,它表示与文件描述符fd 关联的终端设备。如果fd 没有与终端设备关联,则引发一个异常。
60 os.unlink(path) 删除文件
61 os.utime(path, times) 返回指定的path文件的访问和修改的时间。
62 os.walk(top[, topdown=True[, οnerrοr=None[, followlinks=False]]]) 输出在文件夹中的文件名通过在树中游走,向上或者向下。
63 os.write(fd, str) 写入字符串到文件描述符 fd中. 返回实际写入的字符串长度

Python os path 模块命令集

序号 方法名 作用
1 os.path.abspath(path) 返回绝对路径
2 os.path.basename(path) 返回文件名
3 os.path.commonprefix(list) 返回list(多个路径)中,所有path共有的最长的路径
4 os.path.dirname(path) 返回文件路径
5 os.path.exists(path) 如果路径 path 存在,返回 True;如果路径 path 不存在或损坏,返回 False。
6 os.path.lexists(path) 路径存在则返回 True,路径损坏也返回 True
7 os.path.expanduser(path) 把 path 中包含的 ~ 和 ~user 转换成用户目录
8 os.path.expandvars(path) 根据环境变量的值替换 path 中包含的 $name 和 ${name}
9 os.path.getatime(path) 返回最近访问时间(浮点型秒数)
10 os.path.getmtime(path) 返回最近文件修改时间
11 os.path.getctime(path) 返回文件 path 创建时间
12 os.path.getsize(path) 返回文件大小,如果文件不存在就返回错误
13 os.path.isabs(path) 判断是否为绝对路径
14 os.path.isfile(path) 判断路径是否为文件
15 os.path.isdir(path) 判断路径是否为目录
16 os.path.islink(path) 判断路径是否为链接
17 os.path.ismount(path) 判断路径是否为挂载点
18 os.path.join(path1[, path2[, …]]) 把目录和文件名合成一个路径
19 os.path.normcase(path) 转换path的大小写和斜杠
20 os.path.normpath(path) 规范path字符串形式
21 os.path.realpath(path) 返回path的真实路径
22 os.path.relpath(path[, start]) 从start开始计算相对路径
23 os.path.samefile(path1, path2) 判断目录或文件是否相同
24 os.path.sameopenfile(fp1, fp2) 判断fp1和fp2是否指向同一文件
25 os.path.samestat(stat1, stat2) 判断stat tuple stat1和stat2是否指向同一个文件
26 os.path.split(path) 把路径分割成 dirname 和 basename,返回一个元组
27 os.path.splitdrive(path) 一般用在 windows 下,返回驱动器名和路径组成的元组
28 os.path.splitext(path) 分割路径,返回路径名和文件扩展名的元组
29 os.path.splitunc(path) 把路径分割为加载点与文件
30 os.path.walk(path, visit, arg) 遍历path,进入每个目录都调用visit函数,visit函数必须有3个参数(arg, dirname, names),dirname表示当前目录的目录名,names代表当前目录下的所有文件名,args则为walk的第三个参数
31 os.path.supports_unicode_filenames 设置是否支持unicode路径名

Guess you like

Origin blog.csdn.net/qq_37952052/article/details/130915187