一、文件处理介绍
1 什么是文件
文件是操作系统为用户/应用程序提供的一种操作硬盘的抽象单位
2 为何要用文件
用户/应用程序对文件的读写操作会由操作系统转换成具体的硬盘操作
所以用户/应用程序可以通过简单的读\写文件来间接地控制复杂的硬盘的存取操作
实现将内存中的数据永久保存到硬盘中
user=input('>>>>: ') #user="egon"
3 如何用文件
文件操作的基本步骤:
f=open(...) #打开文件,拿到一个文件对象f,f就相当于一个遥控器,可以向操作系统发送指令
f.read() # 读写文件,向操作系统发送读写文件指令
f.close() # 关闭文件,回收操作系统的资源
上下文管理:
with open(...) as f:
pass
# 向操作系统发送请求,要求操作系统打开文件
f=open(r'C:\Users\silence\PycharmProjects\day1\a.txt',encoding='utf-8')
# f的值是一个文件对象
print(f)
print(f.read())
# 向操作系统发送请求,要求操作系统关闭打开的文件
# 强调:一定要在程序结束前关闭打开的文件
f.close()
# 上下文管理with
with open(r'C:\Users\silence\PycharmProjects\day1\a.txt','r',encoding='utf-8') as f:
read=f.read()
print(read)
# 字符串转密码
# 不能直接使用dict
1.py
with open('a.txt','rt',encoding='utf-8')as f :
auth=f.read()
d=eval(auth)
print(d,type(d))
-----------------------------------
{'name': 's_jun'} <class 'dict'>
a.txt
{"name":"s_jun"}
二、文件操作
一 文件的打开模式
r: 只读模式L(默认的)
w: 只写模式
a: 只追加写模式
二 控制读写文件单位的方式(必须与r\w\a连用)
t : 文本模式(默认的),一定要指定encoding参数
优点: 操作系统会将硬盘中二进制数字解码成unicode然后返回
强调:只针对文本文件有效
b: 二进制模式,一定不能指定encoding参数
优点:
a.txt
{"name":"s_jun"}
1.py
with open('a.txt',mode='rt',encoding='utf-8') as f:
data=f.read()
print(data,type(data))
--------------------------------------------------
{"name":"s_jun"} <class 'str'>
# 图片二进制查看
with open('1.jpg',mode='rb',) as f:
data=f.read()
print(data,type(data))
----------------------------------------
b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\...... <class 'bytes'>
with open('a.txt',mode='rb',) as f:
data=f.read()
print(data,type(data))
print(data.decode('utf-8'))
-----------------------------------
b'{"name":"s_jun"}' <class 'bytes'>
{"name":"s_jun"}
with open('a.txt',mode='rt',encoding='utf-8') as f:
data=f.read()
print(data,type(data))
----------------------------------------------
{"name":"s_jun"} <class 'str'>
# r: 只读模式L(默认的)
# 1 当文件不存时,会报错
# 2 当文件存在时,文件指针指向文件的开头
with open('a.txt',mode='rt',encoding='utf-8') as f:
res1=f.read()
print('111===>',res1)
res2=f.read()
print('222===>',res2)
print(f.read())
print(f.readable())
print(f.writable())
print(f.readline())
print(f.readline())
for line in f:
print(line)
l=[]
for line in f:
l.append(line)
print(l)
print(f.readlines())
-------------------------------------------
111===> {"name":"s_jun"}
222===>
True
False
[]
[]
二 w: 只写模式
# 1 当文件不存时,新建一个空文档
# 2 当文件存在时,清空文件内容,文件指针跑到文件的开头
with open('c.txt',mode='wt',encoding='utf-8') as f:
print(f.readable())
print(f.writable())
f.write('你愁啥\n')
f.write('瞅你咋地\n')
f.write('1111\n2222\n333\n4444\n')
info=['egon:123\n','alex:456\n','lxx:lxx123\n']
for line in info:
f.write(line)
f.writelines(info)
------------------------------------------
False
True
c.txt
你愁啥
瞅你咋地
1111
2222
333
4444
egon:123
alex:456
lxx:lxx123
egon:123
alex:456
lxx:lxx123
with open('c.txt',mode='rb') as f:
print(f.read())
with open('c.txt',mode='wb') as f:
f.write('哈哈哈\n'.encode('utf-8'))
f.write('你愁啥\n'.encode('utf-8'))
f.write('瞅你咋地\n'.encode('utf-8'))
---------------------------------------------------
b'\xe5\x93\x88\xe5\x93\x88\xe5\...... '
c.txt
哈哈哈 你愁啥 瞅你咋地 (\n,回车)
# 三 a: 只追加写模式
# 1 当文件不存时,新建一个空文档,文件指针跑到文件的末尾
# 2 当文件存在时,文件指针跑到文件的末尾
with open('c.txt',mode='at',encoding='utf-8') as f:
print(f.readable())
print(f.writable())
f.write('虎老师:123\n')
----------------------------------------------------
False
True
c.txt
哈哈哈
你愁啥
瞅你咋地
虎老师:123
(\n,回车)
# 在文件打开不关闭的情况下,连续的写入,下一次写入一定是基于上一次写入指针的位置而继续的
with open('d.txt',mode='wt',encoding='utf-8') as f:
f.write('虎老师1:123\n')
f.write('虎老师2:123\n')
f.write('虎老师3:123\n')
d.txt
虎老师1:123
虎老师2:123
虎老师3:123
(\n,回车)
-----------------------------------------------------------------------
with open('d.txt',mode='wt',encoding='utf-8') as f:
f.write('虎老师4:123\n')
d.txt
虎老师4:123
(\n,回车)
---------------------------------------------------------------------------
with open('d.txt',mode='at',encoding='utf-8') as f:
f.write('虎老师1:123\n')
f.write('虎老师2:123\n')
f.write('虎老师3:123\n')
d.txt
虎老师4:123
虎老师1:123
虎老师2:123
虎老师3:123
------------------------------------------
with open('d.txt',mode='at',encoding='utf-8') as f:
f.write('虎老师4:123\n')
d.txt
虎老师4:123
虎老师1:123
虎老师2:123
虎老师3:123
虎老师4:123
(\n,回车)
工具代码:
类型Linux cp 工具
使用:
python .\copyTool.py a.txt aa.txt
# 系统提供的模块 现在用它来接收用户从cmd中输入的参数
import sys
# argv 返回一个数组 里面是cmd中接收的参数 空格分隔
print(sys.argv)
src = sys.argv[1]
dis = sys.argv[2]
if src == dis:
print("源文件与目标文件相同 再见")
# 以读取二进制的模式打开源文件
srcf = open(src, "rb")
# 以写入二进制的模式打开目标文件
disf = open(dis, "wb")
# 从源文件读取 写入到目标文件
for line in srcf:
disf.write(line)
# 关闭资源
srcf.close()
disf.close()
登录注册购物车
users = []
# current_user 当前用户
current_user = ""
# 注册用户
while True:
name = input("请输入用户名:")
# 循环取出所有姓名对比
tag = True
for i in users:
if i["name"] == name:
print("用户名重复 请重试:")
tag = False
break
if False == tag:
continue
password = input("请输入密码:")
confirm_password = input("请再次输入密码:")
if password != confirm_password:
print("两次密码不相同")
continue
else:
users.append({"name": name, "pwd": password})
print("注册成功 请登陆")
current_user = name
break
name = input("请输入用户名:")
pwd = input("请输入密码:")
for user_dic in users:
if user_dic["name"] == name:
if user_dic["pwd"] == pwd:
print("欢迎你:%s" % name)
break
select = input("""
请选择:
1.查看商品列表
2.修改密码
""")
# 商品列表
product_list = [['Iphone7', 5800],
['Coffee', 30],
['疙瘩汤', 10],
['Python Book', 99],
['Bike', 199],
['ViVo X9', 2499],
]
# 创建一个字典用于保存购物车数据
product_dict = {}
if select == "1":
while True:
for i in product_list:
print("%d %s" % (product_list.index(i) + 1, i))
text = input("请输入序号:")
if text == "quit":
break
num = int(text)
if num > 0 and num < 7:
print("加入购物车")
product = product_list[num - 1]
# 如果商品已经存在购物车中就更新数量和价格 否则加进去
if product[0] in product_dict:
dict1 = product_dict[product[0]]
# 更新价格
dict1["price"] = dict1["price"] + product[1]
# 更新数量
dict1["count"] = dict1["count"] + 1
else:
product_dict[product[0]] = {"name": product[0], "price": product[1], "count": 1}
else:
print("序号不存在")
elif select == "2":
tag1 = True
while tag1:
oldpwd = input("请输入旧密码:")
for u in users:
if u["name"] == current_user:
if oldpwd == u["pwd"]:
newpwd = input("请输入新密码:")
if newpwd == "quit":
tag1 = False
break
u["pwd"] = newpwd
tag1 = False
break
else:
print("旧密码不正确")
print(users)
else:
print("输入错误:")
print(product_dict)
冒泡排序
data = [3, 2, 1, 4, 5]
# 排序有两种顺序 从大到小 从小到大
# 从大到小
# 核心思想 依次取出两个相邻元素 比较大小 如果是从大到小
# a b a < b 如果前者小于后者就交换位置
"""
第一圈 5 2 1 3 4 4
第二圈 5 2 3 4 1 3
第三圈 5 3 4 2 1 2
第四圈 5 4 3 2 1 1
结论每一圈比较的次数 是需要比较的元素个数减去1
每一圈比较完毕后都会产生一个具备顺序的元素 在下一圈比较的时候 这个有顺序的元素就不用在比了
比较的圈数为元素个数减1
选择排序 每次找出一个最大值放到列表的前面或后面
"""
# 外层控制比较圈数
for i in range(len(data)-1):
for j in range(len(data)-1-i):
if data[j] > data[j+1]:
data[j], data[j+1] = data[j+1], data[j]
print(data)
三级菜单
menu={
"中国":{
"湖北":{
"武汉":{
"A":{},
"B":{},
"C":{},
},
},
},
"山西":{
"太原":{
"xx区":{
"1":{},
"2":{},
"3":{},
},
},
},
"青铜":{
"黄金":{
"王者":{
"x":{},
"y":{},
"z":{},
},
},
},
}
tag=True
while tag:
menu1=menu
for k in menu1:
print(k)
choice1=input("一: ").strip()
if choice1=='b':
break
if choice1=='q':
tag=False
if choice1 not in menu1:
continue
while tag:
menu2=menu1[choice1]
for key in menu2:
print(key)
choice2=input("二: ").strip()
if choice2=="b":
break
if choice2=='q':
tag=False
if choice2 not in menu2:
continue
while tag:
menu3=menu2[choice2]
for key in menu3:
print(key)
choice3=input("三:").strip()
if choice3=='b':
break
if choice3=='q':
tag=False
if choice3 not in menu3:
continue
while tag:
menu4=menu3[choice3]
for k in menu4:
print(k)
choice4=input("四:").strip()
if choice4=='b':
break
if choice4=="q":
tag=False
if choice4 not in menu4:
continue
金字塔
n=5
for c in range(1,n+1):
for i in range(n-c):
print(' ',end='')
for j in range(2*c-1):
print('*',end='')
print()
n=1
while n <= 8:
print(('x'* n).center(17,' '))
n+=2
n=1
for i in range(0,10):
if i%2==1:
print(("x"*i).center(20,' '))
99乘法口诀表
for i in range(1,10):
for j in range(1,i+1):
print("{}*{}={}\t".format(i,j,i*j),end="")
print()
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。