当前位置:   article > 正文

python中的常用模块_os库和sys库

os库和sys库

os和sys模块

ossys是Python标准库中两个非常重要的模块,它们提供了丰富的方法来与Python解释器以及操作系统交互。

os模块

os模块提供了许多函数,用于处理文件和目录等操作系统任务,如路径管理、执行命令、获取进程信息等。

常用方法:
  • os.getcwd():返回当前工作目录的路径。
  • os.chdir(path):改变当前工作目录到指定的路径。
  • os.listdir(path='.'):列出指定目录下的所有文件和子目录名。
  • os.mkdir(path, mode=0o777):创建一个名为path的文件夹。
  • os.makedirs(name, mode=0o777, exist_ok=False):递归创建目录。
  • os.remove(path) / os.unlink(path):删除指定路径的文件。这两个方法功能相同。
  • os.rmdir(path):删除空目录。
  • os.path.join(a, *p):将多个路径组合后返回。

sys模块

sys模块提供了一系列有关Python解释器和它的环境的函数和变量。

常用方法:
  • sys.argv:命令行参数List,第一个元素是程序本身路径。
  • sys.exit([arg]):退出程序,可选参数可以是给定的返回值或错误消息。
  • sys.version:获取Python解释器版本信息。
  • sys.path:返回模块搜索路径列表。可以被修改(例如添加新路径)以影响未来模块加载行为。

代码示例

import os
import sys

print(" os模块 ".center(100, "-"))
# 获取当前工作目录
current_dir = os.getcwd()
print("Current Directory:", current_dir)

# 列出当前目录下所有内容 , 包括文件和文件夹
print(os.listdir('.'))

# 创建新目录
new_dir = "sample_directory"
if not os.path.exists(new_dir):
    # mode = 0o777 是指定权限 ,如果文件夹存在会报错 : FileExistsError: [Errno 17] File exists: 'sample_directory'
    os.mkdir(new_dir, mode=0o777)
    print(f"Directory {new_dir} created.")

# 删除目录
if os.path.exists(new_dir):
    os.rmdir(new_dir)
    print(f"Directory {new_dir} deleted.")

# 改变当前工作目录
os.chdir("/Users/fangyirui/PycharmProjects/")
print(os.listdir())

# 递归新目录,exist_ok 代表忽略是否已经存在
os.makedirs("sample_directory2/aa/aaa/aaa", mode=0o777, exist_ok=True)

# 获取文件的绝对路径
print(os.path.abspath("xxxx"))

# 获取文件的基本名称,不管文件是否存在
print(os.path.basename("/path/to/somefile.txt"))

# 文件或文件夹改名
os.rename("sample_directory2", "sample_directory3")

print(" sys模块 ".center(100, "-"))
# 打印命令行参数
print("Script name:", sys.argv[0])
for i, arg in enumerate(sys.argv[1:], 1):
    print(f"Arg {i}: {arg}")

# 检查Python版本号
# hasattr 方法:返回对象是否具有给定名称的属性。这是通过调用getattr(obj, name)并捕获AttributeError来完成的。
if not hasattr(sys, "hexversion") or sys.hexversion < 0x03070000:
    sys.exit("This script requires Python 3.7 or later")

print(sys)
print(sys.hexversion)
print(sys.version)
print(0x03070000)

# 添加新搜索路径,python会在这些路径下搜索模块
new_path = "/path/to/add"
if new_path not in sys.path:
    sys.path.append(new_path)

print(sys.path)

sys.exit("测试打印退出信息")

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
注意

其中sys.argv在pycharm下需要以下配置才行

在这里插入图片描述

在这里插入图片描述

time模块

time模块是Python的标准库之一,它提供了各种与时间相关的函数。这个模块对于执行时间相关的操作,如获取当前时间、延迟程序执行、测量性能等非常有用。

常用方法:

  • time.time():返回自纪元(Epoch,即1970年1月1日 00:00:00 UTC)以来经过的秒数。
  • time.sleep(seconds):使程序暂停指定的秒数。
  • time.localtime([secs]):将从纪元以来的秒数转换为本地时间。如果不提供参数,则默认使用当前时间。
  • time.gmtime([secs]):和localtime类似,但返回UTC时区的struct_time对象。
  • time.strftime(format[, t]):将一个struct_time(默认为当前时间)转换为给定格式的字符串。
  • time.strptime(string[, format]):将格式化字符串转换回struct_time对象。
示例:
import time

# 获取当前时间戳
timestamp = time.time()
print("Current Timestamp:", timestamp)

# 将时间戳转换为本地时间
local_time = time.localtime(timestamp)
print("Local Time:", local_time)

# 格式化日期和时间
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", local_time)
print("Formatted Time:", formatted_time)

# 程序延迟执行
print("Sleeping for 5 seconds...")
time.sleep(5)
print("Awake!")

# 解析日期字符串
date_string = "2023-04-01"
parsed_date = time.strptime(date_string, "%Y-%m-%d")
print(f"Parsed Date: {parsed_date.tm_year}-{parsed_date.tm_mon}-{parsed_date.tm_mday}")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

time.struct_time对象

time.struct_time是Python中time模块定义的一个类,用于表示时间。它是一个具有九个属性的命名元组,这些属性提供了关于日期和时间的详细信息。这种格式便于处理和存储日期时间值。

属性:
  1. tm_year:年份,例如2023
  2. tm_mon:月份,范围从1到12
  3. tm_mday:一个月中的第几天,范围从1到31
  4. tm_hour:小时数,范围从0到23
  5. tm_min:分钟数,范围从0到59
  6. tm_sec:秒数,范围从0到61(60或61是闰秒)
  7. tm_wday:一周中的第几天,星期一为0(范围是0到6)
  8. tm_yday:一年中的第几天,1月1日为1(范围是1到366)
  9. tm_isdst:夏令时标志位。值为1表示当前或给定时间处于夏令时;值为0表示当前或给定时间不处于夏令时;值为-1表示未知。
使用示例

当你使用如time.localtime()time.gmtime()等函数将秒数转换成本地时间或UTC时间时, 这些函数会返回一个填充了上述信息的struct_time对象。

import time

# 获取当前本地时间,并以struct_time形式展示
local_time = time.localtime()
print(local_time)
# 输出可能类似: time.struct_time(tm_year=2023, tm_mon=4, tm_mday=15, ...)

# 访问struct_time对象中特定字段
print("Year:", local_time.tm_year)
print("Month:", local_time.tm_mon)
print("Day of the month:", local_time.tm_mday)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

通过使用这种结构化方式来处理日期和时间数据,在进行比较、计算或格式化输出等操作时更加方便和直观。此外,在需要对日期和时间进行序列化或与其他系统交互时也非常有用。

datetime模块是Python的标准库之一,提供了一系列用于处理日期和时间的类。与time模块相比,它提供了更高级别、更灵活且易于使用的接口来操作日期和时间。这个模块支持日期和时间的算术运算,并且能够对日期和时间进行格式化输出或解析。

datetime模块

主要的类:

  1. datetime.date:表示日期。常用属性有year, month, day。
  2. datetime.time:表示一天中的时间。常用属性有hour, minute, second, microsecond。
  3. datetime.datetime:同时包含日期和时间。
  4. datetime.timedelta:表示两个date、time或datetime实例之间的差(以天、秒、微秒等形式)。
  5. datetime.tzinfo:时区信息对象基类。

常用方法:

  • now() / today():获取当前本地日期或者详细到时分秒的当前本地时间。
  • strftime(format):将date或者datetime对象格式化为字符串。
  • strptime(date_string, format):将格式化字符串转换为date或者datetime对象。

示例:

from datetime import datetime, date, time, timedelta

# 获取当前完整时间
now = datetime.now()
print("Current DateTime:", now)

# 获取今天的日期
today = date.today()
print("Today's Date:", today)

# 创建特定日期和时间
some_date = date(2023, 4, 15)
some_time = time(14, 30)
print("Specific Date:", some_date)
print("Specific Time:", some_time)

# 时间加减
tomorrow = today + timedelta(days=1) # 当前日加上一天
last_week = today - timedelta(weeks=1) # 当前日减去一周
print("Tomorrow's Date:", tomorrow)
print("Date Last Week:", last_week)

# 格式化输出
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted DateTime:", formatted_date)

# 解析字符串为DateTime对象
parsed_datetime = datetime.strptime(formatted_date,"%Y-%m-%d %H:%M:%S")
print("Parsed DateTime:", parsed_datetime)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

节假日倒数脚本

from datetime import datetime, timedelta


def workdays(end_time, chinese_holidays_name):
    start_time = datetime.now()
    # start_time -= timedelta(days=1)
    work_days = 0
    all_days = (end_time - start_time).days
    days_off = [5, 6]
    while start_time.date() < end_time.date():
        # print(start_time, start_time.weekday())
        if start_time.weekday() not in days_off:
            work_days += 1
        start_time += timedelta(days=1)

    print(f"距离【{chinese_holidays_name}】还有{all_days}天,工作日有{work_days}天")


holidays = {
    datetime(2024, 4, 4): "清明",
    datetime(2024, 5, 1): "五一",
    datetime(2024, 6, 8): "端午",
    datetime(2024, 9, 17): "中秋",
    datetime(2024, 10, 1): "国庆",
    datetime(2025, 1, 1): "元旦",
    datetime(2025, 1, 28): "春节"
}

for k, v in holidays.items():
    workdays(k, v)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/838580
推荐阅读
相关标签
  

闽ICP备14008679号