文件的读写操作:
关于文件的读写操作,我们不得不提到系统函数open()函数了。
在使用open()函数时,需要一个变量来接住它,这个变量就相当于一个将Pycharm和文件连接的管道,我们对文件的读写操作都有基于这个管道进行。
open()参数:
open(file,mode,buffering,encoding)
file 是文件路径+文件名,如果该参数有误,则会报错
mode 是读写模式,其值可以是: 'rt' 读取纯文本
'rb' 以二进制形式读取
’wt‘写入纯文本
'wb'以二进制形式写入
'rb'和'wb'可用于对纯文本,图片,音乐,影像类型的文件进行操作
buffering 是缓存
encoding 是编码方式,encoding='utf-8' 可以读取汉字
文件路径:
绝对路径:也称文件的完整路径。例如:D:\测试(test)文件夹\PY.png
相对路径:相对于当前文件(参照)的路径。 ../ 返回上一级目录
读操作:
1.读取纯文本文件时,如果内容含有汉字则会报错
2.在写文件路径的时候,防止误写转义字符,可在字符串前加 r
3.read:可理解为文件被读入了Pycharm
stream = open(r'D:\python\PyCharm\test.txt') #建立通道的动作;防止转义字符,在文件参数上加r
container = stream.read() #读取文件所有内容
result = stream.readable() #判断该文件是否可读
result1 = stream.readline() #若读取过该文件,则返回空行
result2= stream.readlines() #必须是没有读取过的文件
read() 读取所有内容 readable() 判断是否可读,返回值为bool类型 readline() 每次读取一行内容(每行后换行) readlines() 读取所有行内容保存在列表里(每行后有换行符)
写操作:
1.write:可理解为用Pycharm向文件里写内容
2.mode 为 ’w‘ 表示写操作(会覆盖之前内容)
为 'a' 表示在原内容下进行追加写入(不覆盖原内容)
3.每次写操作结束后需要关闭管道,stream.close()
stream = open(r'D:\python\PyCharm\test1.txt','a')
result = stream.writable() #判断文件的可修改性
result1 = stream.write(s) #返回值是写入的字符个数
stream.writelines(['德莱厄斯—SSS\n','卡特琳娜\n'])
stream.close() #每次写操作结束后要关闭流,关闭之后无法写入
write() 向文件写入,参数为字符串形式。返回写入的字符格式
writable() 判断文件是否可修改,返回值是bool类型
writelines() 参数为列表,每写入一个元素就换行
为了便利,我们尽量使用with open() as 管道名: ,来打开一个管道,用来代替 stream = open(),并且最后不用敲stream.close(),自动释放资源
###(读写操作)文件复制###
with open('D:\python\PyCharm\PY.png','rb') as rstream:
container = rstream.read() #读取文件内容
with open(r'D:\python\PyCharm\test\PY.png','wb') as wstream:
wstream.write(container) #写入
print('文件复制完成!')
在使用该代码进行文件复制的时候,需要注意的是with .. as .. : 的格式,以及文件路径的正确。
os模块的使用:
os全称为operatng system ,os模块是Pycharm与文件管理操作系统进行交互的接口。
下面介绍一些
os模块的常用方法:
os.getcwd() 获取当前文件夹的路径
os.mkdir() 在指定路径下,创建一个文件夹,文件夹存在时报错,没有返回值
os.rmdir() 在指定路径下,删除一个文件夹,文件夹不存在时报错,没有返回值
os.listdir() 将指定文件夹里的文件添加到列表里返回
os.remove() 删除文件
os.chdir() 切换目录
os模块下path里的方法:
os.path.join() 有两个字符串参数,用于拼接文件夹路径和文件名
os.path.dirname() 返回参数文件的目录(文件夹路径)
os.path.split() 参数为文件路径;切一刀,返回一个元组,元素分别为文件夹路径和文件名
os.path.splitext() 切一刀,返回一个元组,元素分别为文件路径和文件的扩展名
os.path.isabs() 判断参数是否为绝对路径
os.path.isdir() 判断参数是否为文件夹
os.path.isfile() 判断参数是否为文件
os.path.exists() 判断该文件或文件夹是否存在
os.path.getsize() 返回文件的字节大小
os.path.abspath(__file__) 返回当前文件的绝对路径;参数可换为其他文件的路径
##利用os模块下的方法,写一个函数,完成文件复制的功能
src_path = r'D:\python\PyCharm\test'
target_path = r'D:\测试(test)文件夹'
def copy(src,target):
if os.path.isdir(src) and os.path.isdir(target):
filelist = os.listdir(src)
for file in filelist:
filepath = os.path.join(src,file)
if os.path.isdir(filepath): #如果要复制的是一个文件夹而不是文件,则递归调用该函数
copy(filepath,target)
else:
targetfile = os.path.join(target,file)
with open(filepath,'rb') as rstream:
container = rstream.read()
with open(targetfile,'wb') as wstream:
wstream.write(container)
copy(src_path,target_path) #最终复制给目标文件的只有文件,没有文件夹
函数输入参数为文件夹路径,利用os.listdir()把文件夹下的文件名放到列表容器里,通过os.path.join()对文件夹路径和文件名进行拼接,配合文件的读写操作来完成文件的复制。
判断待复制的文件是否为文件夹,是文件夹则要递归调用该函数,最终复制给目标文件夹的只有文件。
##(低配版)图书管理系统
# 存储数据 D:\测试(test)文件夹\Test1
# 用户注册
def register():
username = input('输入用户名:')
password = input('输入密码:')
repassword = input('确认输入密码:')
if password == repassword:
# 保存信息
with open(r'D:\测试(test)文件夹\Test1\user.txt', 'a') as wstream:
wstream.write('{} {}\n'.format(username, password))
# wstream.writelines([username+' ',password+'\n'])
print('注册成功!')
else:
print('两次输入密码不一致,请再次尝试注册!')
register()
def login():
username = input('输入用户名:')
password = input('输入密码:')
if username and password:
with open(r'D:\测试(test)文件夹\Test1\user.txt', 'r') as rstream:
while True:
user = rstream.readline()
input_user = '{} {}\n'.format(username, password)
if input_user == user:
print('登录成功!')
show_books()
add_books()
break
else:
print('用户名或密码错误,请重新登录!')
login()
def show_books():
print('------图书馆里的书有------')
with open(r'D:\测试(test)文件夹\Test1\books.txt', encoding="utf-8") as rstream:
booklist = rstream.readlines()
for book in booklist:
print(book, end='')
def add_books():
choice = input('请选择你要借阅的书籍:')
choice = choice + '\n'
with open(r'D:\测试(test)文件夹\Test1\books.txt', encoding="utf-8") as rstream:
booklist = rstream.readlines()
print(booklist)
if choice in booklist:
print('借阅成功!')
else:
print('查无此书!')
# register()
# show_books()
login()