# ### tarfile .tar | .tar.gz | .tar.bz2
import tarfile
"""官方說法, .tar.bz2 的壓縮算法,包的大小最小."""
# 1.壓縮檔案
# (1) 建立tar壓縮包 # 10240
tf = tarfile.open("ceshi0513.tar","w",encoding="utf-8")
# (2) 添加檔案打包
# add(路徑,别名)
tf.add(r"E:\python30\day17\ceshi100\1.txt","1.txt")
tf.add(r"E:\python30\day17\ceshi100\2.txt","222")
tf.add(r"E:\python30\day17\ceshi100\3.py","/tmp/3.py")
# (3) 關閉檔案
tf.close()
# .tar.gz 的壓縮包 # 245
tf = tarfile.open("ceshi0514.tar.gz","w:gz",encoding="utf-8")
tf.add(r"E:\python30\day17\ceshi100\1.txt","1.txt")
tf.add(r"E:\python30\day17\ceshi100\2.txt","222")
tf.add(r"E:\python30\day17\ceshi100\3.py","/tmp/3.py")
tf.close()
# .tar.bz2 的壓縮包 # 240 理論上 , 壓縮出來的包最小.
tf = tarfile.open("ceshi0515.tar.bz2","w:bz2",encoding="utf-8")
tf.add(r"E:\python30\day17\ceshi100\1.txt","1.txt")
tf.add(r"E:\python30\day17\ceshi100\2.txt","222")
tf.add(r"E:\python30\day17\ceshi100\3.py","/tmp/3.py")
tf.close()
"""
import zipfile
# (1) 建立壓縮包 345
zf = zipfile.ZipFile("ceshi0512.zip","w",zipfile.ZIP_DEFLATED)
zf.write(r"E:\python30\day17\ceshi100\1.txt","1.txt")
zf.write(r"E:\python30\day17\ceshi100\2.txt","222")
zf.write(r"E:\python30\day17\ceshi100\3.py","/tmp/3.py")
zf.close()
"""
# 2.解壓檔案
tf = tarfile.open("ceshi0514.tar.gz","r",encoding="utf-8")
#extractall(路徑) 解壓所有檔案到某個路徑下
# tf.extractall("ceshi500")
# extract(檔案,路徑) 解壓指定的某個檔案到某個路徑下
tf.extract("222","ceshi600")
tf.close()
# 3.追加檔案
"""隻能對w模式下的打包進行追加,其他的模式不行"""
with tarfile.open("ceshi0513.tar","a",encoding="utf-8") as tf:
tf.add(r"E:\python30\day17\ceshi100\4.php","4.php")
# 對于tar.gz 或者 tar.bz2已經壓縮過的包無法追加檔案
"""
with tarfile.open("ceshi0514.tar.gz","a",encoding="utf-8") as tf:
tf.add(r"E:\python30\day17\ceshi100\4.php","4.php")
"""
# 4.檢視壓縮包
with tarfile.open("ceshi0513.tar","r",encoding="utf-8") as tf:
lst = tf.getnames()
print(lst)
# ### 對tarfile 不能追加的檔案的bug 進行優化.
"""
tarfile 的解決方法 檔案或者檔案夾都可以通過add放到壓縮包中
(1) 先解壓原來的壓縮包
(2) 把要追加的内容放進去
(3) 過濾資料,重新打包
"""
import os
pathvar = os.getcwd()
print(pathvar) # E:\python30\day17
# 壓縮包的路徑
pathvar1 = os.path.join(pathvar,"ceshi0515.tar.bz2")
print(pathvar1)
# 解壓檔案夾的路徑
pathvar2 = os.path.join(pathvar,"ceshi0515")
print(pathvar2)
# 1.先解壓壓縮包
with tarfile.open(pathvar1,"r",encoding="utf-8") as tf:
tf.extractall(pathvar2)
# 2.把追加的内容放進來
import shutil
shutil.copy(r"E:\python30\day17\ceshi100\4.php",pathvar2)
# 3.過濾資料,重新打包
"""過濾掉222這個檔案,剩下的檔案重新打包"""
lst = os.listdir(pathvar2)
print(lst) # ['1.txt', '222', '4.php', 'tmp']
with tarfile.open(pathvar1,"w:bz2",encoding="utf-8") as tf:
for i in lst:
# print(i)
pathnew = os.path.join(pathvar2,i)
print(pathnew)
# add(路徑,别名)
if i != "222":
tf.add(pathnew,i)
# ### zipfile 字尾是zip
import zipfile
# 1.壓縮檔案
# (1) 建立壓縮包 619
zf = zipfile.ZipFile("ceshi0512.zip","w",zipfile.ZIP_DEFLATED)
# (2) 把檔案寫入到壓縮包當中
# write(路徑,别名)
zf.write(r"E:\python30\day17\ceshi100\1.txt","1.txt")
zf.write(r"E:\python30\day17\ceshi100\2.txt","2.txt")
# 可以允許臨時建立一個檔案夾tmp
zf.write(r"E:\python30\day17\ceshi100\3.py","/tmp/3.py")
# (3) 關閉壓縮檔案
zf.close()
# 2.解壓檔案
zf = zipfile.ZipFile("ceshi0512.zip","r")
# ./代表相對于目前路徑
# zf.extractall("./ceshi300")
# zf.extract(檔案,檔案夾)
zf.extract("1.txt","./ceshi400")
zf.close()
# 3.追加檔案
zf = zipfile.ZipFile("ceshi0512.zip","a",zipfile.ZIP_DEFLATED)
zf.write(r"E:\python30\day17\ceshi100\4.php","4.py")
zf.close()
# 使用with文法進行優化 (可以省略close操作) 推薦
with zipfile.ZipFile("ceshi0512.zip","a",zipfile.ZIP_DEFLATED) as zf:
zf.write(r"E:\python30\day17\ceshi100\4.php","6666.py")
# 4.檢視檔案
with zipfile.ZipFile("ceshi0512.zip","r",zipfile.ZIP_DEFLATED) as zf:
lst = zf.namelist()
print(lst)
# ### 購物車 作業要求:(用函數寫)
# 1. 使用者先給自己的賬戶充錢:比如先充3000元。
# 2. 頁面顯示 序号 + 名稱 + 價格 , 如:
# [===========有如下商品供您選擇:===========]
# 序号 名稱 價格
# 1 電腦 1999
# 2 滑鼠 10
# 3 遊艇 20
# 4 美女 998
# n或N 購物車結算
# q或Q 退出程式(如不結算購物車可直接退出)]
# [==========================================]
# 購物車結算
# 3. 使用者輸入選擇的商品序号,然後列印商品名稱及商品價格,并将此商品,添加到購物車,使用者還可繼續添加商品。
# 4. 如果使用者輸入的商品序号有誤,則提示輸入有誤,并重新輸入。
# 5. (1)使用者輸入n為購物車結算,依次顯示使用者購物車裡面的商品,數量及單價
# (2)若充值的錢數不足則讓使用者删除某商品,直至可以購買,若充值的錢數充足,則可以直接購買退出
# (3)退出程式之後,依次顯示使用者購買的商品,數量,單價,以及此次共消費多少錢,賬戶餘額多少
# 6. 使用者輸入Q或者q 直接退出程式。
# ### 購物車小程式
import json
import time
money = 0
goods_lst = []
# 定義一個購物車字典
car = {}
"""
car = {
1:{電腦... }
2:{滑鼠...}
}
"""
with open("shopping_data.json", mode="r+", encoding="utf-8") as fp:
for i in fp:
dic = json.loads(i)
goods_lst.append(dic)
print(goods_lst)
"""
[
0 {'name': '電腦', 'price': 1999}, 1
1 {'name': '滑鼠', 'price': 10}, 2
2 {'name': '遊艇', 'price': 20}, 3
3 {'name': '美女', 'price': 998}, 4
4 {'name': '風油精', 'price': 30} 5
]
"""
def progress(percent):
if percent > 1:
percent = 1
strvar = int(50 * percent) * "#"
print("\r[%-50s] %d%%" % (strvar, int(100 * percent)), end="")
def exe_progress():
recv_size = 0
# 假設檔案總大小是 1028000
total_size = 1028000
while recv_size < total_size:
time.sleep(0.01)
# 一次接受的位元組數是1024
recv_size += 6000
percent = recv_size / total_size
progress(percent)
# 充值
def recharge():
global money
while True:
num = input("請充值吧,大哥")
if num.isdecimal():
print("恭喜你~ 充值成功{}元人民币".format(num))
break
else:
print("充值失敗,非數字.")
# 加載
def loading():
print("加載商品中 ... ")
exe_progress()
print()
# 展示
def show_goods():
strvar = "{}".format("商品名稱").center(18)
print("序号" + strvar + "價格")
# 列印對應的商品
for k, v in enumerate(goods_lst, start=1):
# print(k,v)
v['num'] = k
strvar = "{v[num]:<10}{v[name]:<12}{v[price]}".format(v=v)
print(strvar)
def error():
strvar = """
**************************************************
* 您輸入的選項不存在 , 請重新輸入 *
**************************************************
"""
print(strvar)
time.sleep(1)
def add_car(num):
if num not in car:
car[num] = {
"name": goods_lst[num - 1]["name"],
"price": goods_lst[num - 1]["price"],
"account": 1
}
else:
car[num]["account"] += 1
print(car)
"""
{
序号: 商品描述(字典形式展現)
2: {'name': '滑鼠', 'price': 10, 'account': 1},
3: {'name': '遊艇', 'price': 20, 'account': 1}
}
"""
def show_car(num):
print("*" * 50)
print("您選擇的商品具體資訊:")
print("*-商品名稱:{}".format(car[num]["name"]))
print("*-商品單價:{}".format(car[num]["price"]))
print("*-商品數量:{}".format(car[num]["account"]))
print("已成功添加到購物車~ 請繼續shopping ~")
print("*" * 50)
# 主檔案調用
def main():
# 1.充值
recharge()
# 2.加載中
loading()
# 3.展示商品
show_goods()
# 4.開始購物
sign = True
while sign:
num = input("請輸入您要購買的商品:")
if num.isdecimal():
num = int(num)
add_car(num)
show_car(num)
elif num.upper() == "N":
pass
elif num.upper() == "Q":
pass
else:
# 報錯
error()
main()