Python實現(xiàn)簡單的文件操作合集
更新時間:2022年09月22日 15:25:40 作者:顧城沐心
這篇文章主要為大家詳細介紹了Python實現(xiàn)的一些簡單的文件操作合集,例如:文件的打開,關閉;文件的寫入等,感興趣的小伙伴可以了解一下
一、文件操作
1.打開
r+ 打開存在文件 文件不存在 報錯
file = open("user.txt","r+")
print(file,type(file))
w+ 若是文件不存在 會創(chuàng)建文件
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到此這篇關于Python實現(xiàn)簡單的文件操作合集的文章就介紹到這了,更多相關Python文件操作內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
pandas基礎?Series與Dataframe與numpy對二進制文件輸入輸出
這篇文章主要介紹了pandas基礎Series與Dataframe與numpy對二進制文件輸入輸出,series是一種一維的數組型對象,它包含了一個值序列和一個數據標簽2022-07-07
淺析Python 實現(xiàn)一個自動化翻譯和替換的工具
這篇文章主要介紹了Python 實現(xiàn)一個自動化翻譯和替換的工具,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-04-04

