網站首頁 編程語言 正文
一、文件操作
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("hello\n")
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
原文鏈接:https://blog.csdn.net/m0_56051805/article/details/126982476
相關推薦
- 2023-06-04 Flask框架中的session設置詳解_python
- 2022-05-20 Maven下載安裝配置詳細過程
- 2021-12-12 linux縮減XFS分區格式的根目錄_Linux
- 2022-10-11 C++函數對象Functor與匿名函數對象Lambda表達式詳解_C 語言
- 2023-01-02 C++?命名空間?using聲明使用示例詳解_C 語言
- 2022-05-08 Python+matplotlib實現堆疊圖的繪制_python
- 2022-02-14 linux系統之進程管理詳解_Linux
- 2022-10-12 C語言實現面向對象的方法詳解_C 語言
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支