《毫无障碍学Python》邓文渊著 学习笔记
文件操作
1. open() 函数
open() 函数打开文件
python内建函数 可打开指定文件 用于对文件读取、修改、添加内容
open(filename[,mode][,encode]) 使用方法如下:文件句柄 = open(‘文件路径’, ‘模式’,编码方式)。
#open函数共有8个参数,其中最常用三个:filename(不可省略)、mode、encode(可省、可省 省略用默认值)
- filename 代表要读写文件名 字符串类型 默认当前程序所在目录路径
- mode 用于设置文件打开模式、字符串类型,若省略 则默认读 mode三种取值:r(只读,不可写,不存报错),w(写,会覆盖原文件,不存则自动创建),a(增加模式,写则内容增加到原文件,不存自创)
- mode 补: r(只读), r+(读写,不创建)
w(新建只写), w+(新建读写) 二者均均将之前文件内容覆盖
a(附加写), a+(附加读写)
f = open('D:\\python_code\\a.txt','r')
f.close()
content = '''Hello
My
Name
Is
Lily
''' # 两个'''之间的数据保留原格式
f = open('D:\\python_code\\b.txt','w')
f.write(content)
f.close() #close()函数关闭文件 也可with语句关闭文件 ,with语句后自动结束文件
with open('D:\\python_code\\b.txt','r') as f:
for i in f:
print(i,end=' ')
#将文件读取并显示出来
f = open('D:\\python_code\\a.txt','r')
for line in f:
print(line,end = " ")
f.close()
## encode 指定文件编码模式,一般可设cp950或UTF-8
f=open('D:\\python_code\\a.txt','r',encoding = 'UTF-8')
for line in f:
print(line,end=" ")
f.close()
2.常见文件操作
常见文件操作 | 功能 |
---|---|
close() | 关闭文件,关闭后文件不可进行读写操作 |
flush() | 文件关闭时将数据写入文件,flush()方法,在可在不关闭文件的条件下,强制将缓冲区数据写入文件,并清除缓冲区 |
read([size]) | 读取指定长度的字符,若未指定长度,会读取所有字符 |
readable() | 测试文件是否可读 |
readline([size]) | 读取读取当前指针所在行中长度为size的字符,若省略参数,会读取一整行,包括"\n" |
readlines() | 读取所有行,返回值是一个列表 |
next() | 移动到下一行 |
seek(0) | 将文件移到文件最前面 |
tell() | 返回文件当前位置 |
write(str) | 将指定字符串写入文件中,无返回值 |
writable() | 测试文件是否可写 |
(1)read()读取文件 :从当前指针位置读取指定长度字符,不指定长度,则读取所有字符
f = open('a.txt','r')
str1 = f.read(7) #读取文件中前7个字符
print(str1)
f.close
(2)readlines()读取文件 :读取全部内容,返回值为列表,文件每一行作为列表的一个元素
with open('b.txt','r') as f:
content = f.readlines()
print(type(content)) #显示返回值得数据类型
print(content) #显示文件内容
(3)readline([size])读取文件:读取当前字符指针所在行中长度为size的内容,若省略参数,则读取一整行包括"\n"字符
f = open('b.txt','r',encoding='utf-8-sig')
print(f.readline())
print(f.readline(4))
f.close()
3.文件操作应用
文件操作实现 账号密码管理系统 -_-|||
##文件操作应用
def menu(): #选项菜单函数
os.system('cls')
print("账号、密码管理系统")
print('----------------------')
print("1.新增账号、密码")
print("2.显示账号、密码")
print("3.修改密码")
print("4.删除账号、密码")
print("0.结束程序")
print('----------------------')
def ReadData(): #读文件函数,将数据转换为字典类型返回
with open('d:\\python_code\\password.txt','r',encoding='utf-8-sig') as f:
filedata = f.read() #读取的文件内容filedata为str类型
if filedata != "":
data = ast.literal_eval(filedata) #ast.literal_eval将filedata转化为dict(字典)类型,要求filedata内容字符格式与字典格式相同,即为{“**”:**,“**”:**}
return data
else: return dict()
def disp_data(): #显示账号、密码函数
print("账号\t密码")
print('====================')
for key in data:
print("{}\t{}".format(key,data[key]))
input("按任意键返回主菜单")
def input_data(): #新增账号密码函数
while True:
name = input("请输入账号(Enter==>停止输入)")
if name == "":break
if name in data:
print("{}账号已存在!".format(name))
continue
password = input("请输入密码:")
data[name] = password
with open('d:\\python_code\\password.txt','w',encoding='utf-8-sig') as f:
f.write(str(data))
print("{}已保存完毕".format(name))
def edit_data(): #修改密码函数
while True:
name = input("请输入要修改的账号(按Enter==>停止输入)")
if name == "":break
if not name in data:
print("{}账号不存在".format(name))
continue
print("原密码为{}".format(data[name]))
password = input("请输入新密码:")
data[name] = password
with open('d:\\python_code\\password.txt','w',encoding='utf-8-sig') as f:
f.write(str(data))
input("密码修改完毕,请按任意键返回主菜单")
break
def delete_data(): #删除账户函数
while True:
name = input("请输入要删除的账号(Enter==>停止输入)")
if name == "":break
if not name in data:
print("{}账号不存在!".format(name))
continue
print("确定删除{}的数据".format(name))
yn = input("Y/N")
if(yn=='Y' or yn=='y'):
del data[name]
with open('d:\\python_code\\password.txt','w',encoding='utf-8-sig') as f:
f.write(str(data))
input("{}数据已被删除!".format(name))
break
##############主程序##############
import os,ast
data = dict()
data = ReadData() #读取文件后,转换为字典类型
while True:
menu()
choice = int(input("请输入您的选择:"))
print()
if choice==1:
input_data()
elif choice==2:
disp_data()
elif choice==3:
edit_data()
elif choice==4:
delete_data()
else:
break
print("程序执行完毕!")
运行结果: