首頁 > 軟體

Python實現簡單的檔案操作合集

2022-09-24 14:00:26

一、檔案操作

1.開啟

r+ 開啟存在檔案 檔案不存在 報錯

file = open("user.txt","r+")
print(file,type(file))

w+ 若是檔案不存在 會建立檔案

file = open("user.txt","w+")
print(file,type(file))

2.關閉 

file.close()

3.寫入

file = open("user.txt","w+")
print(file,type(file))
file.write("hellon")
file.close()

4.讀取 

print(file.readlines())

二:python中自動開啟關閉資源

寫入操作

stu = {'name':'lily','pwd':'123456'}
stu1 = {'name':'sam','pwd':'123123'}
#字典列表
stu_list = [stu,stu1]
 
#寫入操作
with open("user.txt",mode='a+') as file:
    for item in stu_list:
        print(item)
        file.write(item['name']+" "+item['pwd']+"n")

讀取操作

#讀取操作
with open("user.txt",mode='r+') as file:
    lines = file.readlines()
    for line in lines:
        line = line.strip() #字串兩端的空格去掉
        print(line)

#讀取操作
with open("user.txt",mode='r+') as file:
    lines = file.readlines()
    for line in lines:
        #字串分割 空格分割出使用者名稱和密碼
        name , pwd = line.split(" ")
        print(name,pwd)

user_list = []
#讀取操作
with open("user.txt",mode='r+') as file:
    lines = file.readlines()
    for line in lines:
        line = line.strip() #字串兩端空格去除 去除n
        name,pwd= line.split(" ") #用空格分割
        user_list.append({'name':name,'pwd':pwd})
    print(user_list)

user_list = []
#讀取操作
with open("user.txt",mode='r+') as file:
    lines = file.readlines()
    for line in lines:
        name,pwd = line.strip().split(" ")
        user_list.append({'name':name,'pwd':pwd})
    print(user_list)

讀寫函數簡單封裝

# 寫入操作 封裝
def write_file(filename,stu_list):
    with open(filename,mode='a+') as file:
        for item in stu_list:
            file.write(item['name'] + " " + item['pwd'] + "n")
#讀取操作 函數封裝
def read_file(filename):
    user_list = []
    with open(filename,mode='r+') as file:
     lines = file.readlines()
    for line in lines:
        name,pwd = line.strip().split(" ")
        user_list.append({'name':name,'pwd':pwd})
    return user_list

到此這篇關於Python實現簡單的檔案操作合集的文章就介紹到這了,更多相關Python檔案操作內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com