Python入门之部分模块介绍

常用系统模块

查看python的帮助 docs.python.org 选择对应的Python版本,找到标准库参考,在标准库参考中会有函数,模块等的介绍

  • shutil模块:实现文件的复制,剪切,删除等操作

>>> import shutil
#通过文件对象拷贝文件
>>> f1 = open('/home/student/dic.txt','rb')
>>> f2 = open('/tmp/sd','wb')
>>> shutil.copyfileobj(f1,f2)
>>> f1.close()
>>> f2.close()

#直接拷贝
>>> shutil.copy('/home/student/dic.txt', '/tmp/sdd')
'/tmp/sdd'

#拷贝目录
>>> shutil.copytree('/home/student/bin', '/tmp/sss')
'/tmp/sss'

#移动文件
>>> shutil.move('/home/student/rpmbuild', '/tmp/lss')
'/tmp/lss'

# 删除目录
>>> shutil.rmtree('/tmp/sss')

#改变文件的属主和属组
>>> shutil.chown('/tmp/lss', user='lisi', group='lisi')
  • subprocess模块:可以调用任何的系统模块

>>> import subprocess
>>> subprocess.run('ls -a ~student', shell=True)
# 执行系统命令,将输出保存到stdout变量中,错误保存到stderr变量中
>>> a = subprocess.run('ls -a ~student', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> a.stdout
>>> a.stderr
b''
>>> a.returncode  # 返回值 $?
0

Python的其他与法风格

  • 链式多重赋值

>>> a = b = 10
>>> b = 15
>>> a
10        # 字符,数字等值不可变
>>> b      # b指向了15数字所在的内存,a未发生改变
15

>>> alist = blist = [0,1.2]
>>> alist
[0, 1.2]
>>> blist
[0, 1.2]
>>> blist[1] = 15
>>> alist            # 列表,字典值可变
[0, 15]
>>> blist     #alist和blist都指向了同一块内存,但这块内存的值是可以发生改变的
[0, 15]
  • 多元赋值

>>> a, b = 'xy'
>>> c, d = 1,2
>>> e, f = (3,4)
>>> g, h = ['asd', 'zxc']
>>> a
'x'
>>> b
'y'
>>> c
1
>>> d
2
>>> e
3
>>> f
4
>>> g
'asd'
>>> h
'zxc'
  • 交换两个变量的值

>>> a, b = 1, 2
>>> a
1
>>> b
2
>>> a, b = b, a
>>> a
2
>>> b
1

标识符

各种各样的名称,如变量,函数,模块,类,统称为标识符
合法的标识符需要满足的条件

  • 首字符必须是字母或下划线
  • 其他字符是字母,下划线或数字
  • 严格区分大小写

关键字

为了实现Python的语法,python保留了一些名字,叫关键字
关键字不能被覆盖

>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
# 判断是否为关键字的方法
>>> 'pass' in keyword.kwlist
True
>>> keyword.iskeyword('in')
True

内键

内键不是关键字,但是内键不建议覆盖
在标准库参考页面中,“内置函数”就是内建。还可以按ctrl+f搜索模块。

>>> type(len)
<class 'builtin_function_or_method'>
>>> len('qrfdsfa')
7
>>> len = 4
>>> len('asdagsg')                # 覆盖后,原有功能会丢失
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

模块文件布局

#!/usr/bin/python3      #解释器
'''模块说明文档
用于help帮助时显示
'''
import os     # 模块导入

debug = True              # 定义全局变量
password = '213afds'

class MyClass:			# 类的定义 
	pass 
	
def func1():            # 函数声明
	pass
def func2():            
	pass

if __name__ == '__main__':     # 程序主体
	pass

案例

  1. 编写一个程序,要求用户输入文件名
  2. 如果文件已存在,要求用户重新输入
  3. 提示用户输入数据,每行数据先写到列表中
  4. 将列表数据写入到用户输入的文件名中

编程思路

1.思考程序的运行方式:交互式?非交互式?
交互式提醒用户输入信息
2.思考程序由哪些功能构成,将这些功能编写成函数.

def get_filename():
    '返回值为文件名的字符串'
def get_content():
    '返回值为内容的字符串列表'
def write_file(fname, content):
    '将内容写入到文件中'

3.编写主程序,按一定的规则调用函数

if __name__ == '__main__': #主程序
   fname = get_filename()
   content = get_content()
   content = ['%s\n' % line for line in content]
   write_file(fname, content)   

4.编写每个函数

import os

def get_filename():
    '返回值为文件名的字符串'
    while 1:
        name = input('请输入文件名:')
        if  not os.path.exists(name):
            break

        print('文件已存在!')

    return name

def get_content():
    '返回值为内容的字符串列表'
    content = []

    print('请输入内容,单独输入end结束内容输入')
    while 1:
        str = input('(end to over)>')
        # str = input('(end to over)>') + '\n'  #给字符列表每个元素添加换行符号,默认输入不记录回车,则会导致列表写入时会在一行
        # if str == 'end\n':
        if str == 'end':
            break

        content.append(str)

    return content

def write_file(fname, content):
    '将内容写入到文件中'
    with open(fname, 'w') as fobj:
        fobj.writelines(content)

if __name__ == '__main__':
    fname = get_filename()
    content = get_content()
    content = ['%s\n' % line for line in content] #给字符列表每个元素添加换行符号,默认输入不记录回车,则会导致列表写入时会在一行
    write_file(fname, content)

在这里插入图片描述

序列对象

  • list将对象转换成列表

>>> list('shdahd')
['s', 'h', 'd', 'a', 'h', 'd']
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  • tuple将对象转换成元组

>>> tuple('asdfdhbd')
('a', 's', 'd', 'f', 'd', 'h', 'b', 'd')
>>> tuple(range(10))
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
  • str将对象转换成字符串

>>> str(['a', 'b', 'c'])
"['a', 'b', 'c']"
>>> a = str(['a', 'b', 'c'])
>>> print(a)
['a', 'b', 'c']
>>> print(a[1])
'
  • reversed函数用于反转对象

>>> import random
>>> a = [random.randint(1,100) for i in range(10)]
>>> print(a)
[56, 58, 43, 59, 17, 97, 93, 7, 86, 38]
>>> reversed(a)
<list_reverseiterator object at 0x7f8e58f22eb8>
>>> list(reversed(a))
[38, 86, 7, 93, 97, 17, 59, 43, 58, 56]

  • sorted函数用于排序

>>> sorted(a)
[7, 17, 38, 43, 56, 58, 59, 86, 93, 97]
  • enumerate函数可同时得到下标和值

>>> enumerate(a)
<enumerate object at 0x7f8e58ebecf0>
>>> list(enumerate(a))
[(0, 56), (1, 58), (2, 43), (3, 59), (4, 17), (5, 97), (6, 93), (7, 7), (8, 86), (9, 38)]
#以元组的形式显示下标和值
>>> for i in enumerate(a):
...     print(i)
... 
(0, 56)
(1, 58)
(2, 43)
(3, 59)
(4, 17)
(5, 97)
(6, 93)
(7, 7)
(8, 86)
(9, 38)
# 分别显示下标和值
>>> for i,j in enumerate(a):
...     print(i,j)
... 
0 56
1 58
2 43
3 59
4 17
5 97
6 93
7 7
8 86
9 38

字符串

  • 字符串的大小比较,是按照字符的码值比较
  • 常用的编码有:ASCII, Lantin-1(ISO8859-1),GB2312,GB18030, GBK,utf8
>>> s = '汉'
>>> print(s)>>> s.encode()   # 将字符串类型转化为bytes类型
b'\xe6\xb1\x89'  # 一个汉字字符占3个字节,1个字节占两位(byte)
>>> a = s.encode()
>>> a
b'\xe6\xb1\x89'
>>> a.decode()   # 讲bytes类型转化为字符串类型
'汉'

字符串格式化操作

>>> '' % () # 如果字符串中只有一项需要替换,()可以省略
''
>>> '%s is %scm long' % ('desk', 10)
'desk is 10cm long'
>>> '%s is %d cm long' % ('desk', 10)  # %d表示需要用整数进行替换
'desk is 10 cm long'
>>> '%d is %d cm long' % ('desk', 10)  # 字符类型的不能转成整数
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not str
>>> '%6s%5d' % ('desk', 10)  # 默认右对齐
'  desk   10'
>>> '%-6s%-5d' % ('desk', 10)  # 负数表示左对齐
'desk  10   '

>>> '%#o' % 10  # 转化为8进制数
'0o12'
>>> '%#x' % 10  # 转化为16进制数
'0xa'
>>> '%f' % (5/3)  
'1.666667'
>>> '%.2f' % (5/3)  # 小数点后保留两位
'1.67'
>>> '%5.2f' % (5/3) # 输出总宽度5,小数点后保留2位,不够宽度空格补齐
' 1.67'
>>> '%e' % 10000
'1.000000e+04'
# 使用format方法进行字符串格式化
>>> '{} is {}cm long'.format('desk', 10)
'desk is 10cm long'
>>> '{1} is {0}cm long'.format(10,'desk')
'desk is 10cm long'

字符串方法

# 之前的判断方法
a = '123456'
b = '123456a'
for i in a :
    if i not in '1234567890':
        print(False)
        break
else:
    print(True)
for i in b:
    if i not in '1234567890':
        print(False)
        break
else:
    print(True)
# 采用字符串方法判断字符串中所有的字符是否为数字
>>> a = '123456'
>>> b = '123456a'
>>> a.isdigit()
True
>>> b.isdigit()
False

>>> s1 = '       heloo    \n'
>>> s1.strip()   # 去除两端空白字符
'heloo'
>>> s1.lstrip()		# 去除左侧空白字符
'heloo    \n'
>>> s1.rstrip()		# 去除右侧空白字符
'       heloo'
>>> a = 'hello. world. ni. hao'
>>> a.split()         # 切割字符串
['hello.', 'world.', 'ni.', 'hao']
>>> a.split('.')    # 以'.'为分隔符,切割字符串
['hello', ' world', ' ni', ' hao']
>>> a = a.split()
>>> a
['hello.', 'world.', 'ni.', 'hao']
>>> '-'.join(a)          # 用-拼接字符串
'hello.-world.-ni.-hao'
>>> a = '-'.join(a)
>>> a.replace('o', '11')  #  将o替换成11
'hell11.-w11rld.-ni.-ha11'
>>> a = 'hello'
>>> a.center(20)      # 居中显示
'       hello        '
>>> a.center(20,'~')
'~~~~~~~hello~~~~~~~~'
>>> a.rjust(20,'~')   # 右对齐
'~~~~~~~~~~~~~~~hello'
>>> a.ljust(20,'~')   # 左对齐
'hello~~~~~~~~~~~~~~~'
>>> a.upper()    # 转大写
'HELLO'
>>> a = a.upper()
>>> a
'HELLO'
>>> a.lower()  # 转小写
'hello'
>>> a = 'hao123'
>>> a.isdigit()  # 都是数字吗
False
>>> a.islower()   # 都是小写吗
True

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值