一、文件操作

1.打开

r+ 打开存在文件 文件不存在 报错

file = open("user.txt","r+")
print(file,type(file))

Python实现简单的文件操作合集

w+ 若是文件不存在 会创建文件

file = open("user.txt","w+")
print(file,type(file))

Python实现简单的文件操作合集

2.关闭 

file.close()

3.写入

file = open("user.txt","w+")
print(file,type(file))
file.write("hello\n")
file.close()

Python实现简单的文件操作合集

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")

Python实现简单的文件操作合集

读取操作

#读取操作
with open("user.txt",mode='r+') as file:
    lines = file.readlines()
    for line in lines:
        line = line.strip() #字符串两端的空格去掉
        print(line)

Python实现简单的文件操作合集

#读取操作
with open("user.txt",mode='r+') as file:
    lines = file.readlines()
    for line in lines:
        #字符串分割 空格分割出用户名和密码
        name , pwd = line.split(" ")
        print(name,pwd)

Python实现简单的文件操作合集

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)

Python实现简单的文件操作合集

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)

Python实现简单的文件操作合集

读写函数简单封装

# 写入操作 封装
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

相关文章: