Python實(shí)現(xiàn)簡(jiǎn)單的文件操作合集
一、文件操作
1.打開
r+ 打開存在文件 文件不存在 報(bào)錯(cuò)
file = open("user.txt","r+")
print(file,type(file))
w+ 若是文件不存在 會(huì)創(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中自動(dòng)開啟關(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ù)簡(jiǎn)單封裝
# 寫入操作 封裝
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到此這篇關(guān)于Python實(shí)現(xiàn)簡(jiǎn)單的文件操作合集的文章就介紹到這了,更多相關(guān)Python文件操作內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python3實(shí)現(xiàn)域名查詢和whois查詢功能
本篇文章給大家分享了python3實(shí)現(xiàn)域名查詢和whois查詢功能的詳細(xì)代碼,有需要的朋友參考學(xué)習(xí)下。2018-06-06
Python實(shí)現(xiàn)連接FTP并下載文件夾
這篇文章主要為大家介紹了如何利用Python實(shí)現(xiàn)鏈接FTP服務(wù)器,并下載相應(yīng)的文件夾,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2022-03-03
python3+PyQt5實(shí)現(xiàn)自定義分?jǐn)?shù)滑塊部件
這篇文章主要為大家詳細(xì)介紹了python3+PyQt5實(shí)現(xiàn)自定義分?jǐn)?shù)滑塊部件,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-04-04
python對(duì)象及面向?qū)ο蠹夹g(shù)詳解
這篇文章主要介紹了python對(duì)象及面向?qū)ο蠹夹g(shù),結(jié)合實(shí)例形式詳細(xì)分析了Python面向?qū)ο笏婕暗念?、?duì)象、方法、屬性等概念與使用技巧,需要的朋友可以參考下2016-07-07
python中json.dumps()和json.loads()的用法
json.dumps()和json.loads()?json.dumps()用于將字典形式轉(zhuǎn)換為字符串,下面這篇文章主要給大家介紹了關(guān)于python中json.dumps()和json.loads()用法的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-09-09

