其他分享
首页 > 其他分享> > 函数与几项简单的模块

函数与几项简单的模块

作者:互联网

检测指针当前位置
with open('a.txt','wt',encoding='utf-8') as f:
    print(f.tell)     # 检测指针当前位置所在
编写日志功能
import time    # 使用 时间模块包
with open('日志的位置',mode='at',encoding='utf-8') as f:
    f.write('%s ...内容\n' % time.strftime('%Y-%m-%d %H:%M:%S'))  后面时间格式
    
# 监控日志
with open('日志位置',mode='rb') as f:
    f.seek(0,2)               # 指针移动到末尾
    while True:
        line = f.realine()
        if len(line) == 0:
            continue
        else:
            print(line.decode('utf-8'), end='' )
修改文件的两种方式
1.
with open('a.txt',mode='rt',encoding='utf-8') as f:
    res = f.read()
with open('a.txt',mode='wt',encoding='utf-8') as f:
    f.write(res.replace('需要替换的内容...','替换成什么内容...'))

2.
import os

with open('a.txt',mode='rt',encoding='utf-8') as f,\
        open('临时文件名...','wt',encoding='utf-8') as f1:
    for line in f:
        f1.write(line.replace('需要替换的内容...','替换成什么内容...'))
os.remove('a.txt')
os.rename('临时文件名...','a.txt')

函数

1.定义函数与调用函数
def func():             # func = 函数的内存地址
    print('....')    

func()
2.函数定义阶段发生的事情

申请内存空间,把函数体代码放进去,然后把内存地址绑定给函数名

def func():
    print(1)
    print(2)
    
3.函数调用阶段发生的事情:执行函数体代码
def func():
    print(1)
    print(2)
    saadad
    
func()    
# 函数定义阶段只检测语法不执行代码,只有在调用函数时才会执行函数体代码

例1
def bar():
    print('from bar')

def foo():
    print('from foo')
    bar()
                                 #   from foo    
foo()                            #    from bar

例2
def foo():
    print('from foo')
    bar()
    
def bar():
    print('from bar')
                                           #   from foo    
foo()                                       #    from bar
4.函数的参数
例
def add(x,y):
    res = x + y
    print(res)
    
add(2,3)


def func(x,y):
    if x > y:
        print(x)
    else:
        print(y)

func(3333,4444)


def log(user,pwd):
    if user == 'wuc' and pwd == '123'
        print('ok')
    else:
        print('error')
        
log('wuc','123')        
5.函数的返回值 return

函数内可以有多个return,但只要执行一次,整个函数就立即结束,并且将return后的值当作本次调用的产品返回

def max(sal1,sal2):
    if sal1 > sal2:
        return sal1
    else:
        return sal2
res = max(1000,2000)
print(res * 12)

#具体来说函数的返回值有三种形式
# 1 return 值: 返回的就是该值本身/-
# 2 return 值1,值2,值3:返回的是小元组

def func():
    return 111,'aaa',[11,22]

x,y,z = func()
print(x,y,z)

# 没有return或者return无值或者return None:返回的都是None

del func():
    res = 1+2
    return

res = func()
print(res)                 #  None

模块

"""
1 什么是模块
    模块一系列功能的集合体

    模块分为四种通用的类别
      1 使用python编写的.py文件

      2 已被编译为共享库或DLL的C或C++扩展

      3 把一系列模块组织到一起的文件夹(注:文件夹下有一个__init__.py文件,该文件夹称之为包)

      4 使用C编写并链接到python解释器的内置模块

    模块有三种来源:
        1 python自带的模块/库
            内置模块
            标准库

        2 第三方的库

        3 自定义库

2 为何要用模块
    1 拿来主义,提升开发效率
    2 减少代码冗余

3 如何用模块
    import
    from ... import
"""
例
import spam
print(spam.x)
print(spam.f1)
print(spam.f2)

def f1():
    print('xxxxx')
    
spam.f1()
spam.f2()



from spam import x ,f1,f2

def f1():
    print('xxxxx')

f1()

常用模块

时间戳
1. import time  
print(time.time())   1970到现在的秒数

2.格式化字符
print(time.strftime('%Y-%m-%d %H:%M:%S'))

3.结构化时间
obj = time.localtime()
print(obj.tm_year)
print(obj.tm_yday)
print(obj)

obj2 = time.gmtime()   # utc时间
print(obj2)

random模块
# print(random.random())
# print(random.randint(1,3))
# print(random.randrange(1,3))
# print(random.choice([11,"aaa",333]))
# print(random.sample([11,"aaa",333,444],2))

# print(random.uniform(1, 3))

# item=[1,3,5,7,9]
# random.shuffle(item)
# print(item)

# 储备知识
# print(chr(65))
# print(chr(90))
#
# print(ord('A'))
# print(ord('Z'))


import random
                                       # 随机验证码的命令
def make_code(size):
    res = ''
    for i in range(size):
        num = str(random.randint(0,9))
        s = chr(random.randint(65,90))
        res += random.choice([num,s])
    return res


print(make_code(6))
os 模块
import os

# print(os.getcwd())  # pwd

# os.makedirs('a/b/c/d')
# os.rmdir('a/b/c/d')
# os.removedirs('a/b/c/d')
# l = os.listdir(r'D:\py18期\day11')
# print(l)

# print(os.listdir('.'))
# print(os.listdir('..'))
# print(os.listdir('../..'))

# print(os.listdir('.'))
# print(os.listdir('..'))
# print(os.listdir('../..'))

# obj=os.stat('a.txt')  # stat a.txt
# print(obj.st_size)
# print(os.sep)
# print(os.linesep)

# print(os.name)

# print(os.environ)

# os.environ['username'] = "egon"
#
# print(os.environ)

# print(os.path.abspath(r"a\b\c"))

# print(__file__)

# print(os.path.split(r"D:\a\b\c\d.txt"))
# print(os.path.dirname(os.path.dirname(r"D:\a\b\c\d.txt")))
# print(os.path.basename(r"D:\a\b\c\d.txt"))

# print(os.path.exists(r"D:\py18期\day11\代码\a"))
# print(os.path.exists(r"D:\py18期\day11\代码\a.txt"))
# print(os.path.isfile(r"D:\py18期\day11\代码\a"))
# print(os.path.isfile(r"D:\py18期\day11\代码\a.txt"))
# print(os.path.isdir(r"D:\py18期\day11\代码\a"))
# print(os.path.isdir(r"D:\py18期\day11\代码\a.txt"))

# print(os.path.isabs(r'D:\py18期\day11\代码\a'))

# print(os.path.getsize('a.txt'))
# print(os.path.join('D:\\', "a", 'b', 'c.txt'))
# print(os.path.join('D:\\', "a", "C:\\" 'b', 'c.txt'))


# print(os.path.dirname(os.path.dirname(__file__)))

# res = os.path.normpath(os.path.join(__file__,"..",'..'))
# print(res)
subprocess 模块
import os

# tasklist | findstr python.exe
# taskkill /F /PID 30060
# os.system('tasklist | findstr chrome')
# res = os.system('tasklist')
# print('='*50)
# print(res)

import subprocess
import time

obj = subprocess.Popen('tasklist',shell=True,
                 stdout=subprocess.PIPE,
                 stderr=subprocess.PIPE
                 )
# print('hello')
# time.sleep(3)

res1 = obj.stdout.read()
res2 = obj.stderr.read()
print(res1.decode('gbk'))
print(res2)

标签:txt,函数,res,模块,print,path,几项,os,def
来源: https://www.cnblogs.com/wu-min/p/14876198.html