目录
os.path.split(path) 与 os.path.splitext(path)
1.读操作
# 1.读操作------------
# 打开文件:open()函数
# (1)open()
# (2)参数:
# open(file, mode='r', buffering=None, encoding=None,
# errors=None, newline=None, closefd=True): # known special case of open
# 文件名/路径,模式(默认是rt: read text,txt的文本文件)
# PS:如果是图片形式的话,mode就不能使用默认的rt形式了,则需要使用将mode的值改为'rb',读取二进制
# (3)open()的返回值:stream(管道)
# 需要使用stream.read() 读取管道中的内容
# read() 读取所有内容--------------------------
stream = open(r'D:\Python\code\functionstudy\aa.txt')
container = stream.read()
print(container)
# 输出文件内容:
# hello this is my text file
# hhhh
# woshi
# readable() 判断是否可读,返回布尔类型--------------------------
check_read = stream.readable()
print(check_read)
# True
# readline() 逐行读取,每次读取一行内容--------------------------
stream = open(r'D:\Python\code\functionstudy\aa.txt')
while True:
# 读完一行会加一个/n
line = stream.readline()
print(line)
if not line:
break
# hello this is my text file
#
# hhhh
#
# woshi
#
print('--------------')
# readlines() 读取所有行保存到列表中--------------------------
stream = open(r'D:\Python\code\functionstudy\aa.txt')
list1=stream.readlines()
id=0
for i in list1:
print('list1中的第{}个元素为:{}'.format(id,i))
id+=1
# 结果:
# list1中的第0个元素为:hello this is my text file
#
# list1中的第1个元素为:hhhh
#
# list1中的第2个元素为:woshi
2.写操作
# 2.写操作------------
# mode='w'的时候,会清空原文件内容,再写入内容=================================================
stream = open(r'D:\Python\code\functionstudy\aa.txt','w')
# writable(): 是否可写
check_write = stream.writable()
print(check_write)
# True
# stream.write()
con='''
悄悄是别离的笙箫
沉默是今晚的康桥
再别康桥
'''
# 将con写入txt文件
res1 = stream.write(con)
print(res1)
# 32
# 在写入一个内容
res2 = stream.write('白居易')
print(res2)
# 3
'''
目前aa.txt中的内容为:
悄悄是别离的笙箫
沉默是今晚的康桥
再别康桥
白居易
'''
# so: 当open()中的mode为w且write()写入的时候,会先清空原来文件中的内容,再写入内容
# 释放资源
stream.close()
# stream.writelines()
stream = open(r'D:\Python\code\functionstudy\aa.txt','w')
stream.writelines(['秋蝉','庆余年','锦衣之下'])
# 此时文件中:【并没有换行】
# 秋蝉庆余年锦衣之下
stream = open(r'D:\Python\code\functionstudy\aa.txt','w')
stream.writelines(['秋蝉\n','庆余年\n','锦衣之下\n']) # 自己手动加上换行\n
# 此时文件中:
# 秋蝉
# 庆余年
# 锦衣之下
# mode='a'的时候,会在原有文件内容的基础上追加内容。a=append=================================================
stream = open(r'D:\Python\code\functionstudy\aa.txt','a')
stream.writelines(['pig\n','happy\n','colleage\n'])
# 此时文件中:
# 秋蝉
# 庆余年
# 锦衣之下
# pig
# happy
# colleage
3.文件复制操作
# 3.文件复制操作------------
# 读+写操作
# 单个文件复制<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
# 示例1:将D:\Python\code\functionstudy\pic目录下的wanzi.jpg复制到D:\Python\code\functionstudy中
# with 结合open使用,可以帮助我们自动释放资源
# 读取文件内容
with open(r'D:\Python\code\functionstudy\pic\wanzi.jpg','rb') as stream:
container = stream.read()
# 打开目标文件
with open(r'D:\Python\code\functionstudy\wanzi.jpg','wb') as wstream:
# 写入内容
wstream.write(container)
print('图片复制成功!') # 此时可在目标文件夹下查看到复制过来的图片
# 批量复制<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
# 需要引入os模块
import os
print(os.path) # <module 'ntpath' from 'D:\\Python\\Anaconda\\lib\\ntpath.py'>,ospath及时ntpath
# 当前文件所在的目录的绝对路径
print(os.path.dirname(__file__)) # D:/Python/code/functionstudy
# os.path小练习:将一个文件复制到当前文件所在目录下《《《《《《《《《《《《《《《《《《《《《《《《《
# 读取文件内容
with open(r'D:\Python\code\functionstudy\pic\plan.png','rb') as stream:
container = stream.read()
# 获取原来文件名
file = stream.name # 返回原始路径:D:\Python\code\functionstudy\pic\wanzi.jpg
filename = file[file.rfind('\\')+1:] # 使用切片查找到文件名
# 获取当前文件所在的目录(绝对目录)
path_dir = os.path.dirname(__file__)
# 将当前目录与文件名进行拼接
path_file = os.path.join(path_dir,filename)
with open(path_file,'wb') as wstream:
# 写入内容
wstream.write(container)
print('图片复制成功!') # 此时可在目标文件夹下查看到复制过来的图片
4. os模块详解
相对路径与绝对路径
'''
相对路径与绝对路径
'''
# 判断是否是绝对路径《《《《《《《《《《《《《《《《《《《《《《《《《
print(os.path.isabs(r'D:\Python\code\functionstudy\pic\plan.png'))
# True
# 相对路径:《《《《《《《《《《《《《《《《《《《《《《《《《
# ../ 上一级
# ../../ 上一级的上一级
# os.path.dirname(__file__):获取当前文件所在文件夹的路径《《《《《《《《《《《《《《《《《《《《《《《《《
path = os.path.dirname(__file__)
print(path) # D:/Python/code/functionstudy
# 根据相对路径获得其绝对路径:os.path.abspath()《《《《《《《《《《《《《《《《《《《《《《《《《
path2 = os.path.abspath('word.docx')
print(path2) # D:\Python\code\functionstudy\word.docx
# 获取当前文件的绝对路径 《《《《《《《《《《《《《《《《《《《《《《《《《
path_current = os.path.abspath(__file__)
print(path_current) # D:\Python\code\functionstudy\func01.py
# os.getcwd(): 获取当前文件所在文件夹的路径《《《《《《《《《《《《《《《《《《《《《《《《《
os.getcwd()
# 判断os.getcwd()得到的内容是否文件
path_file = os.path.isfile(os.getcwd())
print(path_file) # False
# 判断os.getcwd()得到的内容是否目录
path_direc = os.path.isdir(os.getcwd())
print(path_direc) # True
# os.getcwd() 的作用等同于 os.path.dirname(__file__)
print(os.getcwd()) # D:\Python\code\functionstudy
os.path.split(path) 与 os.path.splitext(path)
# os.path.split(path) 分割文件-文件名 作用等同于rfind()
# os.path.split(path): 返回一个元组-->(目录名,文件名)《《《《《《《《《《《《《《《《《《《《《《《《《
path = r'D:\Python\code\functionstudy\func01.py'
res = os.path.split(path)
print(res)
# 返回值:
# ('D:\\Python\\code\\functionstudy', 'func01.py')
# os.path.splitext(path) 分割文件与扩展名,得到(文件,扩展名)《《《《《《《《《《《《《《《《《《《《《《《《《
path = r'D:\Python\code\functionstudy\func01.py'
res = os.path.splitext(path)
print(res)
# 返回值:
# ('D:\\Python\\code\\functionstudy\\func01', '.py')
os.path.getsize(path)
# os.path.getsize(path) 得到文件大小《《《《《《《《《《《《《《《《《《《《《《《《《
path = r'D:\Python\code\functionstudy\func01.py'
res = os.path.getsize(path)
print(res) # 33150
os.path.join(path,paths)
# os.path.join(path,paths) 在路径path的基础上进行增加路径
path = r'D:\Python\code\functionstudy\func01.py'
res1 = os.path.join(path,'pic')
res2 = os.path.join(path,'pic','wanzi.jpg')
print(res1)
print(res2)
# 输出:
# D:\Python\code\functionstudy\func01.py\pic
# D:\Python\code\functionstudy\func01.py\pic\wanzi.jpg
os中与文件夹操作有关的函数
创建目录——os.mkdir()
# 创建文件夹:
# os.mkdir()
# 文件夹已经存在的时候会报错
import os
dir_create = os.mkdir(r'D:\Python\code\functionstudy\demo')
print(dir_create)
# None
判断文件夹是否存在——os.path.exists()
# 为了解决文件夹已经存在的时候会报错,
# 可以加一个判断是否存在的条件:os.path.exists()
if not os.path.exists(r'D:\Python\code\functionstudy\demo'):
dir_create = os.mkdir(r'D:\Python\code\functionstudy\demo')
print(dir_create)
删除目录——os.rmdir()
# 删除目录:rmdir(),removedirs()。【都是只能删除空文件夹,否则会报错】
f = os.rmdir(r'D:\Python\code\functionstudy\demo')
print(f)
# None
删除文件——os.remove()
# 删除文件:remove()
f = os.remove(r'D:\Python\code\functionstudy\word.docx')
print(f)
# None
删除文件夹、文件综合运用
# 删除一个(里面可能含有文件的)文件夹
path = r'D:\Python\code\functionstudy\temp'
# 列出文件夹下的文件
filelist = os.listdir(path)
print('文件夹下的文件有:',filelist)
# 文件夹下的文件有: ['aa.txt', 'wanzi.jpg']
# 遍历list,逐一删除
for file in filelist:
path1 = os.path.join(path,file)
os.remove(path1)
else:
# 文件夹里面已经没有文件了,可以删除文件夹了
os.rmdir(path)
print('删除成功啦!')
# 删除成功啦!
切换目录——os.chdir()
# 切换目录:chdir()
f = os.chdir(r'D:\Python\code\functionstudy\pic')
print(f) # None
path = os.getcwd()
print('当前路径:',path) # 当前路径: D:\Python\code\functionstudy\pic
案例:复制文件夹内容到另一文件夹
复制文件夹内容到另一文件夹1:
# 复制文件夹
src_path = r'D:\Python\code\functionstudy\demo'
tar_path = r'D:\Python\code\functionstudy\pic'
def copy(src_path, tar_path):
# 判断原目录和目标目录是否文件夹
if os.path.isdir(src_path) and os.path.isdir(tar_path):
# 获取原文件夹内文件
filelist = os.listdir(src_path)
# 遍历
for file in filelist:
path = os.path.join(src_path,file)
with open(path,'rb') as rstrem:
container = rstrem.read()
path1 = os.path.join(tar_path,file)
with open(path1,'wb') as wstream:
wstream.write(container)
else:
print('复制完毕!')
# 调用函数
copy(src_path, tar_path)
# 复制完毕!
复制文件夹内容到另一文件夹2【1的加强版】:
def copy(src_path, tar_path):
# 判断原目录和目标目录是否文件夹
if os.path.isdir(src_path) and os.path.isdir(tar_path):
# 获取原文件夹内文件
filelist = os.listdir(src_path)
# 遍历
for file in filelist:
path = os.path.join(src_path,file)
# 判断path是否文件夹
if os.path.isdir(path):
# 递归调用copy
copy(path,tar_path)
else:
# 【会将文件直接复制到另一个目录中,原始的文件夹并不会复制过去,只是取出文件复制过去】
with open(path,'rb') as rstrem:
container = rstrem.read()
path1 = os.path.join(tar_path,file)
with open(path1,'wb') as wstream:
wstream.write(container)
else:
print('复制完毕!')
5.文件是一种持久化保存的方法——案例:注册 登录模块
# 文件是一种持久化保存的方法
# list,元组,字典都是保存到内存,不会持久保存
# 注册模块
def regis():
uname = input('输入用户名:')
upwd = input('输入密码:')
repwd = input('再次输入密码:')
if upwd == repwd:
# 保存到文件
with open(r'D:\Python\code\functionstudy\user.txt','a') as wstream:
wstream.write('{} {}\n'.format(uname, upwd))
print('注册成功!')
else:
print('密码不一致!注册失败!')
# 登录模块
def login():
uname = input('输入用户名:')
upwd = input('输入密码:')
if uname and upwd:
with open(r'D:\Python\code\functionstudy\user.txt','r') as rsteam:
while True:
user = rsteam.readline()
# 读完的时候
if not user:
print('用户名或密码错误!')
break
# 构造成文件中的数据形式
input_uname = '{} {}\n'.format(uname,upwd)
if user == input_uname:
print('登录成功')
break
login()
文件部分完成!学习快乐!