python入门day13文件操作

#文件操作
#读的时候文件不存在就会报错,写的时候不存在就自动创建
'''
文件上传
保存log

系统函数:
open(file,mode,buffering,encoding)


mode:
r读
w写
a扩展(追加)
b二进制
t文本文件
默认rt读文本文件
读写是对于pycharm而言
读是从别的地方(本地文件)读到pycharm
写是从pycharm写到别的地方(本地文件)

读:
stream = open(path/filename,'rt')--->返回值:stream(管道)
container = stream.read()--->读取管道中的内容

注意:如果传递的path/filename有误,则会报错FileNotFoundError
     如果读取的是图片等非纯文本文件则不能用默认的读取方式rt


'''
#读文本文件
stream = open(r'D:\pythonFile\wenjian.txt')#默认mode是rt
container = stream.read()
print(container)#读取出文件的内容
# hello
# www

result=stream.readable()#判断这个文件是否可以读取
print(result)#Ture

line = stream.readline()#读一行
print(line)#这里输出空白,因为上面stream.read()已经把流的东西全部读完了,这里就读不到了


stream2 = open(r'D:\pythonFile\wenjian2.txt')
while True:
    line = stream2.readline()#读一行
    print(line)
    if not line:
        break
'''
hello

www


'''
stream3 = open(r'D:\pythonFile\wenjian2.txt')
lines=stream3.readlines()
print(lines)#['hello\n', 'www']



'''
总结:
read()读取全部内容
readline() 每次读取一行内容
readlines() 读取所有的行保存到列表
readable() 判断是否可以读
'''




#读非文本文件---用默认的rt会报错
stream2 = open(r'D:\pythonFile\wen.doc','rb')#默认mode是rt,但是doc并不是文本文件
container = stream2.read()
print(container)#输出一堆二进制出来

#写文件
'''
stream=open(r'path/filename','w')
mode 是'w'表示写操作

方法:
    write(内容) 每次把原本内容清空再写当前内容
    writelines(Iterable) 没有换行效果,需要自己手动换行
    stream.writelines(['l3','l4','l5\n','l6\n'])

模式mode='a'  不清空原有内容,而是在原有内容上追加
'''


stream = open(r'D:\pythonFile\a.txt','w')

s='''
你好!
    欢迎您。。
'''
result = stream.write(s)
print(result)#返回
stream.write('龙五')
stream.write('龙五2')
stream.writelines(['l3','l4','l5\n','l6\n'])
stream.close()
'''

你好!
    欢迎您。。
龙五龙五2l3l4l5
l6
'''
#每次写文件时,都会把里面原有的内容先清空,在把当前写的全部内容写进去

文件复制&自动释放管道资源

#文件的复制--读写&&os模块
'''
源文件:
目标文件:
'''
'''
stream=open('')
container=stream.read()
stream.close
'''
#使用with结合open使用,可以帮我们自动释放资源
with open(r'D:\pythonFile\wenj\bxg.jpg','rb') as stream:
    container=stream.read()
    with open(r'D:\pythonFile\wenj\bxg2.jpg','wb') as wstream:
        wstream.write(container)
print('文件复制完成!')

文件的复制

#多个文件的复制---os模块(一个模块里面会有很多函数)
'''
模块:xxx.py
     os.py操作系统内置模块---与文件操作相关

总结:
os.path
os.path.dirname(__file__)返回当前文件所在目录
os.path.join(path,filename)在path路径下拼接文件名
'''

import os

print(os.path)
path=os.path.dirname(__file__)#获取当前文件所在文件目录(文件夹)
print(path)
'''
<module 'ntpath' from 'C:\\Users\\Areio\\AppData\\Local\\Programs\\Python\\Python36\\lib\\ntpath.py'>
D:/pythonFile/hanshu/method5
'''
result=os.path.join(path,'a1.jpg')
print(result)#D:/pythonFile/hanshu/method5\a1.jpg


with open(r'D:\pythonFile\wenj\bxg.jpg','rb') as stream:
    container=stream.read()
    file=stream.name
    filename=file[file.rfind('\\')+1:]#截取原来的文件名

    path=os.path.dirname(__file__)
    path1=os.path.join(path,filename)
    with open(path1,'wb') as wstream:
        wstream.write(container)
print('文件复制完成!')

os模块的使用(os.path)

import os

#绝对路径D:\pythonFile\wenj\bxg.jpg
#相对路径:Method4\func01.py
result = os.path.isabs(r'D:\pythonFile\wenj\bxg.jpg')#是否是一个绝对路径
print(result)#True

r=os.path.isabs(r'..\method4\func01')
print(r)#False


#获取当前文件所在文件夹的路径(只定位到文件夹)
#dir--directory 目录 文件夹
path=os.path.dirname(__file__)
print(path)


#通过相对路径得到绝对路径
path=os.path.abspath('func04.py')
print(path)#D:\pythonFile\hanshu\method5\func04.py

#上面一个得到我所在文件夹,我兄弟文件所在路径,接下来我想得到我自己的绝对路径

#获取当前文件的绝对路径
r=os.path.abspath(__file__)#当前文件的路径
r2=os.getcwd()#当前文件所在文件夹路径,类似os.path.dirname(__file__)
print(r)
print(r2)
'''
D:\pythonFile\hanshu\method5\func05.py
D:\pythonFile\hanshu\method5
'''


r=os.path.isfile(os.getcwd())#是否是一个文件
print(r)#False

r=os.path.isdir(os.getcwd())#是否是一个目录
print(r)#True

#获取文件名
path=r'D:\pythonFile\wenj\bxg.jpg'
result=os.path.split(path)
print(result)
#('D:\\pythonFile\\wenj', 'bxg.jpg') 将文件路径和文件名分割出来存在元组
print(result[-1])#bxg.jpg

#获取扩展名
result=os.path.splitext(path)
print(result)#('D:\\pythonFile\\wenj\\bxg', '.jpg')
print(result[-1])#.jpg


#获取文件大小
size=os.path.getsize(path)
print(size)#244092  单位是字节

'''
总结:
os.path常用函数

dirname
join
split
splitext
getsize

isabs
isfile
isdir
'''

os模块的使用(os)

#前面讲的是os.path里面函数
#接下来我们来看os里面函数
import os

#当前文件所在文件夹路径
dir = os.getcwd()
print(dir)#D:\pythonFile\hanshu\method5

#返回指定路径下所有文件和文件夹名字保存到列表
all=os.listdir(r'D:\pythonFile\hanshu')
print(all)#['.idea', 'method', 'method2', 'method3', 'method4', 'method5']


#创建文件夹
# if not os.path.exists(r'd:\p3'):
#     f=os.mkdir(r'd:\p3')
#     print(f)

#删除空的文件夹(只能删除空的)
# f=os.rmdir(r'd:\p3')
# print(f)



#删除文件
# os.remove(r'd:\afa.txt')

#删除非空文件夹
# path=r'c:\p3\p4'
# filelist = os.listdir(path)
# for file in filelist:
#     path1=os.path.join(path,file)
#     os.remove(path1)
# else:#把目录里的文件全部删除后,就可以删除空目录p4了
#     os.rmdir(path)


#切换目录
path = os.getcwd()#查询当前目录
print(path)#D:\pythonFile\hanshu\method5

f = os.chdir(r'D:\pythonFile')
print(f)
path = os.getcwd()#查询当前目录
print(path)#D:\pythonFile


'''
总结:
os模块下方法:
os.getcwd()获取当前文件夹所在目录路径
os.listdir()#返回指定路径下所有文件和文件夹名字保存到列表
os.mkdir()创建文件夹
os.rmdir()删除空文件夹
os.remove()删除文件
os.chdir()切换目录
'''

多个文件的复制

import os
#文件复制
src_path=r'd:\p1' #目录名
target_path=r'd:\p2' #目录名
#将src_path文件夹下的文件全部复制到target_path下

#封装成函数
def copy(src,target):
    if os.path.isdir(src) and os.path.isdir(target):#如果src是一个文件夹
        filelist = os.listdir(src)#浏览文件夹里面的东西
    for file in filelist:
        path=os.path.join(src,file)#绝对路径
        with open(path,'rb') as stream:
            container = stream.read()
            path1=os.path.join(target,file)
            with open(path1,'wb') as stream:
                stream.write(container)
    else:
        print('复制完毕')

#调用函数
copy(src_path,target_path)

文件及文件夹下文件的复制

import os
#如果src_path文件夹下又有目录呢?不仅仅只有文件

src_path=r'd:\p3' #目录名
target_path=r'd:\p4' #目录名

def copy2(src_path,target_path):
    filelist=os.listdir(src_path)#查看这个目录下的所有文件包括文件夹的名字
    print(filelist)#['a.txt', 'b.txt', 'ww']
    for file in filelist:#file可能是文件夹名也可能是文件名
        path = os.path.join(src_path,file)
        #判断是文件还是文件夹
        if os.path.isdir(path):#如果是一个文件夹
            #递归调用
            target_path1=os.path.join(target_path,file)
            os.mkdir(target_path1)  # 创建子文件夹名
            copy2(path,target_path1)

        else:
            with open(path,'rb') as stream:
                container = stream.read()
                path1=os.path.join(target_path,file)
                with open(path1,'wb') as stream:
                    stream.write(container)
    else:
        print('复制完成')

#调用
copy2(src_path,target_path)

图书管理系统例子

'''
回顾:
文件:
文件操作:
    open()
    path,filename:
        path:
            绝对路径
            相对路径
    mode:
    读: rb r
    写: wb w

    stream=open(file,mode)
    stream.read()
    stream.write()
    stream.close()

    with open(file,mode) as stream:
        ...

os模块

os.path常用函数:
dirname  获取指定文件目录
join  拼接获取新的路径
split  分割(文件目录,文件名)
splitext  分割(文件目录、文件名,文件扩展名)
getsize  获取文件大小

isabs  判断是否是绝对路径
isfile  判断是否是文件
isdir  判断是否是目录

os常用函数:
os.getcwd()获取当前文件夹所在目录路径
os.listdir()#返回指定路径下所有文件和文件夹名字保存到列表
os.mkdir()创建文件夹
os.rmdir()删除空文件夹
os.remove()删除文件
os.chdir()切换目录
'''

#例子,图书管理系统
#持久化保存:文件
#list 元组,字典-->内存

#用户注册
def register():
    username=input('输入用户名:')
    password=input('输入密码:')
    repassword=input('输入确认密码:')

    if password==repassword:
        #持久化到文件
        with open(r'D:\pythonFile\wenj\book\users.txt','a') as stream:
            stream.write('{} {}\n'.format(username,password))
        print('用户注册成功!')
    else:
        print('密码不一致')



#用户登录
def login():
    username = input('输入用户名:')
    password = input('输入密码:')
    if username and password:
        #查看输入的与数据库的是否一致
        with open(r'D:\pythonFile\wenj\book\users.txt') as stream:
            while True:
                user=stream.readline()#admin 123456\n
                if not user:
                    print('用户名或密码输入有误')
                    break
                input_user='{} {}\n'.format(username,password)
                if user==input_user:
                    #找到用户不继续读取
                    print('用户登录成功')
                    break


def show_books():
    print('----图书馆里面的图书有:-------')
    with open(r'D:\pythonFile\wenj\book\books.txt','r',encoding='utf8') as stream:
        books = stream.readlines()
        for book in books:
            print(book,end='')
#调用函数
# register()
# login()
show_books()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值