七秒鱼记忆~
每天进步一点点!!!
#文件操作
#os模块
#获取当前文件的路径(绝对路径)
import os
print(os.path.abspath(__file__))
#获取文件的目录
print(os.path.dirname(os.path.abspath(__file__)))
#路径拼接
a =os.path.dirname(os.path.abspath(__file__))
print(os.path.join(a,'test.txt'))
#创建文件目录,先获取文件目录的路径,然后再创建
t =os.path.join(a,'test')
if not os.path.exists(t):
    os.mkdir(t)
#判断是否是一个文件夹
print(os.path.isdir(t))
#判断是否是一个文件
print(os.path.isfile(t))
#判断路径是否存在
print(os.path.exists(t))

#文件读取,open()
#1、打开文件,open(文件路径,mode='r',encoding='utf-8')
#2、读取文件
#3、关闭文件
d =os.path.dirname(os.path.abspath(__file__))
demo =os.path.join(a,'demo.txt')
f =open(demo,encoding='utf-8')  #打开,指定编码格式读取
# print(f.read())  #读取
# f.readline()  #读取一行
print(f.readlines()) #读取所有的数据,以列表的的方式存储
f.close()  #关闭

#方式二
with open(demo,encoding='utf-8') as f:
    f.read()

#写入文件
#mode:
# r:读取;
# a:追加;
# w:写入;
# b:二进制,用于读取图片,音频
d =os.path.dirname(os.path.abspath(__file__))
demo =os.path.join(a,'demo.py')
f =open(demo,mode='a',encoding='utf-8')
f.write('abcdefg')  #写入
f.close()


#异常处理
# try...except... 捕获异常
# try...except...finally... 无论有没有报错,程序都会执行
#raise 抛出异常
posted on 2021-04-20 17:24  fishing~  阅读(48)  评论(0)    收藏  举报