os 系统交互模块

os是python中内置的一个模块
This module provides a portable way of using operating system dependent functionality.
该模块提供了一种与操作系统相关功能的方法,和liniu系统命令相似,提供类似用代码操作系统的功能。
一般接收的是字符串或字节,返回相应的数据类型。

import os
'''
os模块主要是操作文件夹的,根据不同的操作系统有不同的结果,相对于sys模块,sys主要是看现在你所在的文件路径和系统环境变量的,操作本机系统
'''

os.mkdir('dirname')  # 在本目录下新建了一个叫dirname文件夹
os.makedirs('dirname1/dirname2')  # 在本目录下新建了一个dirname1的文件夹,里面有个dirname2文件夹

os.rmdir('dirname')  # 删除本目录下的dirname文件夹,在没有文件的情况的可以删
os.removedirs('dirname1/dirname2')  # 删除文件夹和里面包含的文件夹

ret = os.listdir('D:\学习资料')  # 显示'D:\学习资料'下的所有文件夹和文件名
print(ret)

print(os.stat('D:\学习资料\Daily Task\shopping_car代码.py'))  # 统计指定的文件中的内容
os.stat_result(st_mode=33206, st_ino=3659174697258831, st_dev=2953153744, st_nlink=1, st_uid=0, st_gid=0, st_size=4587, st_atime=1535957805, st_mtime=1534235542, st_ctime=1535957805)

ret1 = os.path.abspath('shopping_car代码.py')  # 显示绝对路径
print(ret1)  # D:\学习资料\Daily Task\shopping_car代码.py

ret2 = os.path.abspath('3, os 模块.py')  # 绝对路径就是从根目录起一直到文件名
print(ret2)  # D:\学习资料\Daily Code and experience\day23 时间模块\3, os 模块.py

path = 'D:\学习资料\Daily Task\shopping_car代码.py'
ret = os.path.split(path)  # 返回一个元组,一个是路径,一个是文件名
print(ret)  # ('D:\\学习资料\\Daily Task', 'shopping_car代码.py')
ret1 = os.path.dirname(path)  # 显示文件路径
print(ret1)  # D:\学习资料\Daily Task
ret2 = os.path.basename(path)  # 显示本文件名
print(ret2)  # shopping_car代码.py

res = os.path.exists('shopping_car代码.py')  # 查看此文件路径是否存在,一定要绝对路径,不可以传相对路径
print(res)  # False
res = os.path.exists('D:\学习资料\Daily Task\shopping_car代码.py')
print(res)  # True

r1 = os.path.isfile('D:/学习资料/Daily Task/shopping_car代码.py')  # 是否是文件
r2 = os.path.isdir('D:/学习资料/Daily Task/')  # 是否是路径
print(r1, r2)  # True True

ret = os.path.join('D:/学习资料/Daily Task', 'day23')
ret = os.path.abspath(ret)
print(ret)  # D:\学习资料\Daily Task\day23

size = os.path.getsize('D:/学习资料/Daily Task/shopping_car代码.py')
print(size)  # 4587 文件大小
size = os.path.getsize('D:/学习资料/Daily Task')
print(size)  # 4096 文件夹大小不能测
size = os.path.getsize('D:\学习资料\Daily Code and experience')
print(size)  # 4096 文件夹大小信息

windows 都是4096
linux,mac文件夹大小 3264

os.system('bash command')
os.popen('bash command').read()
os.getcwd()
os.chdir('dirname')

操作系统命令
python代码

os.system('dir')  # 以字符串的形式来执行操作系统的命令
exec  # 以字符串的形式来执行python代码

ret = os.popen('dir')  # 获取本文件夹中所有文件和大小
print(ret.read())
eval  以字符串的形式来执行python代码,且返回结果

print('--> cwd: ', os.getcwd())  #  D:\学习资料\Daily Code and experience\day23 时间模块
open('file', 'w').close()  # 文件在执行这个文件的目录下创建了,
不是当前被执行的文件所在的目录,而是执行这个文件所在的目录,
工作目录在哪儿,所有的相对目录文件的创建,都是在哪儿执行这个文件,就在哪儿创建

os.chdir('D:\学习资料\Daily Code and experience')
open('file3', 'w').close()
print(os.getcwd)  # <built-in function getcwd>

print(__file__)  # 本文件路径  D:/学习资料/Daily Code and experience/day23 时间模块/3, os 模块.py



python源码中常用的os模块方法

  • os.chdir Change the current working directory to path.

    This function can support specifying a file descriptor. The descriptor must refer to an opened directory, not an open file.

  • os.getcwdb()
    Return a bytestring representing the current working directory.

  • os.listdir(path=’.’)
    Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order, and does not include the special entries ‘.’ and ‘..’ even if they are present in the directory.

  • os.mkdir(path, mode=0o777, *, dir_fd=None)
    Create a directory named path with numeric mode mode.

  • os.makedirs(name, mode=0o777, exist_ok=False)
    Recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory.

  • os.remove(path, *, dir_fd=None)
    Remove (delete) the file path. If path is a directory, OSError is raised. Use rmdir() to remove directories.

  • os.removedirs(name)
    Remove directories recursively. Works like rmdir() except that, if the leaf directory is successfully removed,

  • os.rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
    Rename the file or directory src to dst. If dst is a directory, OSError will be raised.

  • os.renames(old, new)
    Recursive directory or file renaming function.

  • os.rmdir(path, *, dir_fd=None)
    Remove (delete) the directory path. Only works when the directory is empty, otherwise, OSError is raised.

  • os.stat(path, *, dir_fd=None, follow_symlinks=True)
    Get the status of a file or a file descriptor. Perform the equivalent of a stat() system call on the given path.

  • os.popen(cmd, mode=’r’, buffering=-1)
    Open a pipe to or from command cmd. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is ‘r’ (default) or ‘w’.

os.makedirs('dirname1/dirname2')    可生成多层递归目录
os.removedirs('dirname1')    若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
os.mkdir('dirname')    生成单级目录;相当于shell中mkdir dirname
os.rmdir('dirname')    删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
os.listdir('dirname')    列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
os.remove()  删除一个文件
os.rename("oldname","newname")  重命名文件/目录
os.stat('path/filename')  获取文件/目录信息

os.system("bash command")  运行shell命令,直接显示
os.popen("bash command).read()  运行shell命令,获取执行结果
os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
os.chdir("dirname")  改变当前脚本工作目录;相当于shell下cd

os.path
os.path.abspath(path) 返回path规范化的绝对路径
os.path.split(path) 将path分割成目录和文件名二元组返回 
os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素 
os.path.basename(path) 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.exists(path)  如果path存在,返回True;如果path不存在,返回False
os.path.isabs(path)  如果path是绝对路径,返回True
os.path.isfile(path)  如果path是一个存在的文件,返回True。否则返回False
os.path.isdir(path)  如果path是一个存在的目录,则返回True。否则返回False
os.path.join(path1[, path2[, ...]])  将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
os.path.getatime(path)  返回path所指向的文件或者目录的最后访问时间
os.path.getmtime(path)  返回path所指向的文件或者目录的最后修改时间
os.path.getsize(path) 返回path的大小

猜你喜欢

转载自blog.csdn.net/weixin_42233629/article/details/82387924