日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

Python實現(xiàn)簡單的文件操作合集_python

作者:顧城沐心 ? 更新時間: 2022-11-13 編程語言

一、文件操作

1.打開

r+ 打開存在文件 文件不存在 報錯

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

w+ 若是文件不存在 會創(chuàng)建文件

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

2.關(guān)閉?

file.close()

3.寫入

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

4.讀取?

print(file.readlines())

二:python中自動開啟關(guān)閉資源

寫入操作

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)

讀寫函數(shù)簡單封裝

# 寫入操作 封裝
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")
#讀取操作 函數(shù)封裝
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

原文鏈接:https://blog.csdn.net/m0_56051805/article/details/126982476

欄目分類
最近更新