亲宝软件园·资讯

展开

Python文件操作

顾城沐心 人气:0

一、文件操作

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

加载全部内容

相关教程
猜你喜欢
用户评论