目录
1.f.seek的应用
import time
with open('access.log', mode='rb') as f:
# 1、将指针跳到文件末尾
# f.read() # 错误
f.seek(0,2)
while True:
line=f.readline()
if len(line) == 0:
time.sleep(0.3)
else:
print(line.decode('utf-8'),end='')
2.文件修改的两种方式
文件修改的两种方式
方式一:文本编辑采用的就是这种方式
实现思路:将文件内容发一次性全部读入内存,然后在内存中修改完毕后再覆盖写回原文件
优点: 在文件修改过程中同一份数据只有一份
缺点: 会过多地占用内存
with open('c.txt',mode='rt',encoding='utf-8') as f:
res=f.read()
data=res.replace('alex','dsb')
print(data)
with open('c.txt',mode='wt',encoding='utf-8') as f1:
f1.write(data)
方式二:
实现思路:以读的方式打开原文件,以写的方式打开一个临时文件,一行行读取原文件内容,修改完后写入临时文件...,删掉原文件,将临时文件重命名原文件名
优点: 不会占用过多的内存
缺点: 在文件修改过程中同一份数据存了两份
import os
with open('c.txt', mode='rt', encoding='utf-8') as f, \
open('.c.txt.swap', mode='wt', encoding='utf-8') as f1:
for line in f:
f1.write(line.replace('alex', 'dsb'))
os.remove('c.txt')
os.rename('.c.txt.swap', 'c.txt')
f = open('a.txt')
res = f.read()
print(res)
3.函数基本使用
1、什么是函数
函数就相当于具备某一功能的工具
函数的使用必须遵循一个原则:
先定义
后调用
2、为何要用函数
1、组织结构不清晰,可读性差
2、代码冗余
3、可维护性、扩展性差
3、如何用函数
先定义
三种定义方式
后调用
三种调用方式
返回值
三种返回值的形式
"""
一、先定义
定义的语法
'''
def 函数名(参数1,参数2,...):
"""文档描述"""
函数体
return 值
'''
形式一:无参函数
def func():
# x
# print(
print('哈哈哈')
print('哈哈哈')
print('哈哈哈')
定义函数发生的事情
1、申请内存空间保存函数体代码
2、将上述内存地址绑定函数名
3、定义函数不会执行函数体代码,但是会检测函数体语法
调用函数发生的事情
1、通过函数名找到函数的内存地址
2、然后加口号就是在触发函数体代码的执行
print(func)
func()
示范1
def bar(): # bar=函数的内存地址
print('from bar')
def foo():
# print(bar)
bar()
print('from foo')
foo()
示范2
def foo():
# print(bar)
bar()
print('from foo')
def bar(): # bar=函数的内存地址
print('from bar')
foo()
示范3
def foo():
# print(bar)
bar()
print('from foo')
foo()
def bar(): # bar=函数的内存地址
print('from bar')
形式二:有参函数
def func(x,y): # x=1 y=2
print(x,y)
func(1,2)
形式三:空函数,函数体代码为pass
def func(x, y):
pass
三种定义方式各用在何处
1、无参函数的应用场景
def interactive():
name=input('username>>: ')
age=input('age>>: ')
gender=input('gender>>: ')
msg='名字:{} 年龄:{} 性别'.format(name,age,gender)
print(msg)
interactive()
interactive()
interactive()
interactive()
2、有参函数的应用场景
def add(x,y): # 参数-》原材料
# x=20
# y=30
res=x + y
# print(res)
return res # 返回值-》产品
# add(10,2)
res=add(20,30)
print(res)
3、空函数的应用场景
def auth_user():
"""user authentication function"""
pass
def download_file():
"""download file function"""
pass
def upload_file():
"""upload file function"""
pass
def ls():
"""list contents function"""
pass
def cd():
"""change directory"""
pass
二、调用函数
1、语句的形式:只加括号调用函数
interactive()
add(1,2)
2、表达式形式:
def add(x,y): # 参数-》原材料
res=x + y
return res # 返回值-》产品
赋值表达式
res=add(1,2)
print(res)
数学表达式
res=add(1,2)*10
print(res)
3、函数调用可以当做参数
res=add(add(1,2),10)
print(res)
三、函数返回值
return是函数结束的标志,即函数体代码一旦运行到return会立刻
终止函数的运行,并且会将return后的值当做本次运行的结果返回:
1、返回None:函数体内没有return
return
return None
2、返回一个值:return 值
def func():
return 10
res=func()
print(res)
3、返回多个值:用逗号分隔开多个值,会被return返回成元组
def func():
return 10, 'aa', [1, 2]
res = func()
print(res, type(res))
homework
# 1、编写文件修改功能,调用函数时,传入三个参数(修改的文件路径,要修改的内容,修改后的内容)既可完成文件的修改
# 方式一:# 操作系统同时打开两个文件,占用操作两个资源
import os
def file_change(src_file, old, new):
with open(src_file,'r',encoding='utf-8') as f,open('copy.txt','w',encoding='utf-8') as w:
for line in f:
line.replace(old,new)
w.write(line)
os.rename('copy.txt',src_file)
# 方式二:操作系统只打开
def file_change2(src_file, old, new):
list=[]
with open(src_file,'r',encoding='utf-8') as f:
for line in f:
line.replace(old,new)
list.append(line.strip())
with open(src_file, 'w', encoding='utf-8') as w:
for line in list:
w.write(line)
# 2、编写tail工具
def tail_access(file_name):
import time
with open(f'{file_name}', mode='rb') as f:
f.seek(0, 2)
while True:
line = f.readline()
if len(line) == 0:
time.sleep(0.3)
else:
print(line.decode('utf-8'))
# 3、编写登录功能
user_info={'user':None}
def login():
user_name = input('请输入用户名:').strip()
user_pwd = input('请输入密码:').strip()
if user_name == 'tank' and user_pwd == '123':
user_info['user']=user_name
print('登录成功')
else:
print('登录失败')
# 4、编写注册功能
def register():
user_name = input('请输入用户名:').strip()
user_pwd = input('请输入密码:').strip()
re_pwd = input('请再次输入密码:').strip()
if user_pwd == re_pwd:
print('注册成功')
else:
print('注册失败')
# ATM功能实现,数据来源db.txt
# 1.充值功能
def pay_money(username):
dic = {} # 用于存放用户名与金额
with open('db.txt', 'r', encoding='utf-8') as f:
for i in f:
user, money = i.strip().split(':')
dic[user] = int(money)
if username not in dic:
print('用户不存在,退出程序')
return
while True:
money = input('请输入充值金额:')
if not money.isdigit():
print('请输入数字:')
continue
money = int(money)
dic[username] += money
with open('db.txt', 'w', encoding='utf-8') as w:
for user, money in dic.items():
w.write(f'{user}:{money}\n')
break
pay_money('tank')
# 1.转账功能
def transfer(user_A, user_B, transfer_money):
dic = {} # 用于存放用户名与金额
with open('db2.txt', 'r', encoding='utf-8') as f:
for i in f:
user, money = i.strip().split(':')
dic[user] = int(money)
if not user_info.get('user'):
login()
if dic[user_A] not in dic:
print('转账用户不存在')
return
if dic[user_B] not in dic:
print('收款用户不存在')
return
if dic.get(user_A) >= transfer_money:
dic[user_A] -= transfer_money
dic[user_B] += transfer_money
with open('db2.txt', 'w', encoding='utf-8') as w:
for user, money in dic.items():
w.write(f'{user}:{money}\n')
# 3.提现功能
def withdraw(username, int_moeny):
dic = {}
with open('db3.txt', 'r', encoding='utf-8') as f:
for i in f:
user, money = i.strip().split(':')
dic[user] = int(money)
if username not in dic:
print('用户不存在,退出程序')
return
if dic.get(user) >= int_moeny:
dic[username] -= int_moeny
with open('db3.txt', 'w', encoding='utf-8') as w:
for user, money in dic.items():
w.write(f'{user}:{money}\n')
# 4.查询余额
def withdraw(username):
dic = {}
with open('db3.txt', 'r', encoding='utf-8') as f:
for i in f:
user, money = i.strip().split(':')
dic[user] = int(money)
if username not in dic:
print('用户不存在,退出程序')
return
return dic.get(username)
返回