您现在的位置是:网站首页> 编程资料编程资料
Python实现简单的文件操作合集_python_
2023-05-25
519人已围观
简介 Python实现简单的文件操作合集_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文件操作内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
您可能感兴趣的文章:
相关内容
- Python argparse模块实现解析命令行参数方法详解_python_
- Python中np.random.randint()参数详解及用法实例_python_
- Python中tqdm的使用和例子_python_
- media配置及把用户头像从数据库展示到前端的操作方法_python_
- python 镜像环境搭建总结_python_
- Python创建SQL数据库流程逐步讲解_python_
- Python爬取奶茶店数据分析哪家最好喝以及性价比_python_
- 使用python生成大量数据写入es数据库并查询操作(2)_python_
- Python sklearn分类决策树方法详解_python_
- python中elasticsearch_dsl模块的使用方法_python_
