四、文件操作與處理

一、文件處理介紹

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()




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章