Python实现简单的文件操作合集
目录
- 一、文件操作
- 1.打开
- 2.关闭
- 3.写入
- 4.读取
- 二:python中自动开启关闭资源
一、文件操作
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
到此这篇关于Python实现简单的文件操作合集的文章就介绍到这了,更多相关Python文件操作内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
赞 (0)