Python趣事-8

本文简要介绍了Python的os和shutil模块,包括os模块的获取当前路径、更改路径、执行系统命令以及获取系统名称等功能,以及shutil模块中复制、删除、移动文件和文件夹的操作。提醒读者,这只是基本用法,深入学习应查阅官方文档。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简介

1.os模块

2.shutil模块

3.格式化模块(pprint/textwrap)

注意:这里只是简单介绍这些模块的简单使用方法,如果需要深入请查看官方文档

os模块

  • os.getpwd():获取当前路径
  • os.chdir():更改当前路径,注意这里指的是程序运行时更改路径哈,配合其他函数才能看到效果
  • os.system():相当于在系统控制台运行某一命令
  • os.name:返回系统名称
def main():
    print(os.getcwd())

    # 返回上一级目录
    print(os.chdir('..'))

    # 创建一个新的文件夹
    print(os.system('mkdir fu'))

    print(os.name)

这里写图片描述


shutil模块

常用于操作文件或文件夹,os模块下也提供了一些对于文件的操作

  • shutil.copyfile(file1,file2):复制文件
  • shutil.copytree(dir1,dir2):复制文件夹
  • shutil.rmtree(dir):删除文件夹
  • shutil.move(path1, path2):移动文件或文件夹
  • os.romve(file):删除文件,shutil模块未提供删除文件

在谈格式化

import reprlib

# pretty printer
import pprint

# textwrap模块格式段落文本适合给定的屏幕宽度:
import textwrap

# 模版
from string import Template

def main():
    print(repr('123'))
    print(repr(set('supercalifragilisticexpialidocious')))

    # 定制的缩写显示大或深层嵌套的容器:
    print(reprlib.repr(set('supercalifragilisticexpialidocious')))

    print('------------')

    t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta', 'yellow'], 'blue']]]
    # 第二个参数表示对每一行输出的字符进行限制
    pprint.pprint(t,width=40)
    print('------------')

    w = '''
The wrap() method is just like fill() except that it returns
a list of strings instead of one big string with newlines to separate
the wrapped lines.
    '''

    # 对段落文本进行格式化
    print(textwrap.fill(w,width=40))
    print('------------')


    # 字符模版
    te = Template('${village}folk send $$10 to $cause.')
    print(te.substitute(village='Nottingham', cause='the ditch fund'))

    ma = dict(village='Nottingham', cause='the ditch fund')
    print(te.substitute(**ma))
    print(te.substitute(ma))
#   如果没有对应的key,将会抛出KeyError
#   安全转换
#   t.safe_substitute()


if __name__ == '__main__':
    main()

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值