Python学习--Day 16

123.文件的追加和写操作

  • 写操作,write()家族:
    writable()——判断文件是不是可写
    write()——写文本的时候常用
    writelines()——写字符的时候常用
    在使用读写操作后,通常会使用stream.close()
    举例:
stream = open(r'C:\Users\10727\Desktop\q.txt','w')
s = '''
Hello!
    I am Amy.
'''
con = stream.write(s)
print(con)
stream.write('Tom') # 继续追加书写
stream.close() # 释放管道资源
  • 如果先close再write就不会执行,会报错。
  • 写文件的特点:mode是w模式,表示写操作,write(内容),但是这样书写会先将源文件中的内容清空,然后再书写对应的内容
  • writelines()
    writelines()内要放可迭代的数据,比如字符串、列表等。注意每个可迭代的项目书写完毕后不会自动换行,如果想换行必须自己添加\n
stream = open(r'C:\Users\10727\Desktop\q.txt','w')
stream.writelines(['赌神','赌圣','药神'])
  • mode='a’表示追加
    使用a作为mode,不会将原来文件中的内容删除,而是继续进行添加。
stream = open(r'C:\Users\10727\Desktop\q.txt','a') # 使用a模式
stream.writelines(['赌神','赌圣','药神'])
  • stream.name()——返回流中的文件的文件路径。

124.文件复制和os简单操作

  • 文件复制:必须创建两个管道,一个管道将原文件读到Pycharm,另一个管道将文件写给目标文件夹中。
    使用with结合open使用,可以帮助我们自动释放管道资源,不必再close。
    使用with进行复制的示例:
with open(r'C:\Users\10727\Desktop\q.txt','r') as stream:
    container = stream.read()
    with open(r'C:\Users\10727\Desktop\f.txt','w') as wstream:
        wstream.write(container)
  • 将一个文件夹中的所有文件传输到另一个文件夹中,不能使用open,因为open是打开一个特定的文件,一个文件夹是不支持被open的,我们需要借助os模块进行文件夹的复制。另外请记住,如果目标文件夹中不存在文件名为f.txt的文件,那么就先创建该文件,再打开。
  • os模块——import os后就可以使用os中的很多函数了。
    os.path.dirname(__file__)——得到当前文件所在的文件夹路径,并以字符串的格式返回。
    result = os.path.join(path,'具体文件名')——将path文件夹路径与具体文件名连接起来,不能使用join要使用os下的join。
    示例:
import os
with open(r'C:\Users\10727\Desktop\q.txt','r') as stream:
    container = stream.read()
	path = os.path.dirname(__file__)
	path1 = os.path.join(path,'f.txt')
    with open(path1,'w') as wstream:
        wstream.write(container)
  • 综合训练,结合前面的字符串rfind等查找文件名的操作:(值得仔细看一下)
with open(r'C:\Users\10727\Desktop\q.txt','r') as stream:
    container = stream.read()
    print(stream.name)
    file = stream.name
    filename = file[file.rfind('\\')+1:] # 字符串查找的知识内容,以这种方式定位了文件的文件名。
	path = os.path.dirname(__file__)
	path1 = os.path.join(path,filename) # 将路径、文件名结合起来。
    with open(path1,'w') as wstream:
        wstream.write(container)

125.回顾

  • 发现自己匿名函数的地方掌握的不太好,要巩固看一下。
    min()、min()、sorted()都有key参数,要将func的值赋给key,再使用。
    map(func,list),reduce(),filter(func, list),只要将func位置用lambda填充就可以。
  • 总结,没有新东西,跟着走一遍复习就可以。

126.路径讲解(相对和绝对)

  • 在pycharm中一个不算技巧的快捷键,Ctrl+左键,可以快速查看当前函数或模块库的本地源码。
  • 绝对路径:从根源开始的路径,完整的路径,isabs()——判断一个路径是不是绝对路径。
  • 相对路径:针对于当前文件路径而产生的,项目中用的多,../表示往上跳一级,当前文件的上一级。
    记录一下老师上课使用过的一些例子。
r = os.path.isabs(r'c:\p1\girl.jpg')
print('-->',r)

x = os.path.isabs(r'../../images/girls.jpg')
print('-->',x)

t = os.path.isabs('images/girls.jpg')
print('-->',t)
  • 获取绝对路径的一些方法:
    path = os.path.dirname(__file__)——获取当前文件夹所在的路径
    os.path.abspath('aa.txt')——默认aa.txt在当前工作文件的同级,通过相对路径得到绝对路径
    os.path.abspath(__file__)——获取当前文件的绝对路径
    os.getcwd()——获得当前文件的工作目录,与path = os.path.dirname(__file__)类似

127.os模块

  • os.path.split(path),将path分隔为两个部分,分别是文件名和其他路径,返回值是元组类型。
    下面是例子:(对比124的综合训练,有两种方式可以根据完整路径得到文件名)
import os
path = r'C:\Users\10727\Desktop\q.txt'
result = os.path.split(path)
print(result)
# 打印结果:
# ('C:\\Users\\10727\\Desktop', 'q.txt')
  • os.path.splittext(path),将扩展名和其他分隔开,可以判断文件的类型,返回值还是元组。
import os
path = r'C:\Users\10727\Desktop\q.txt'
result = os.path.splitext(path)
print(result)
# 打印结果:
# ('C:\\Users\\10727\\Desktop\\q', '.txt')
  • os.path.getsize(文件名)——返回文件的大小,单位字节。
  • join()的应用示例:
path = r'C:\Users\10727\Desktop\q.txt'
result = os.path.join(os.getcwd(),'file','a','aa.jpg')
print(result)
# 输出结果:
# C:\Users\10727\PycharmProjects\untitled\file\a\aa.jpg
  • os.path.exists()——判断路径下的文件存不存在
  • 总结:常用的os.path中的函数:
    dirname()
    join(),可以多个参数,一直往下套(参考上面的例子)
    splitext()
    split()
    getsize()
    isabs()——是绝对路径吗
    isfile()——是一个文件吗
    isdir()——是文件夹吗
    exists()——文件存在吗
  • os中常用的函数:
    os.getcwd(path)——获得当前文件的工作目录
    os.listdir(path)——返回指定目录下所有的文件和文件夹的名字,浏览文件夹,返回值是一个字符串的列表。
    os.mkdir(r'c:\p3')——没有返回值,此处是在c盘下创建p3文件夹
    os.rmdir(r'c:\p3')——没有返回值,只能移除空的文件夹,文件夹中有文件会报错:OSError: [WinError 145] 目录不是空的
    os.removedirs(r'c:\p3')——与上面的rmdir()一样
    os.remove(r'c:\p3\p4\aa.txt')——移除文件
    os.chdir(r'c:\p1')——没有返回值,切换目录的功能,类似cmd中的cd命令
filelist = os.listdir(path)
for file in filelist: # 遍历文件,将他们全部删除
	path1 = os.path.join(path,file)
	os.remove(path1)
else: # 遍历完成,将目录删除
	os.rmdir(path)

128.复制文件夹

  • 复制文件夹实战,将一个文件夹中的文件全部复制到另一个文件夹中:
    下面是我的答案:已经在本地跑过了,运行成功。考虑了如果文件夹中还有文件夹的情况。
import os
src_path = r'C:\Users\10727\Desktop\src'
target_path = r'C:\Users\10727\Desktop\target'
# 封装成函数
def copy(src, target):
    files = os.listdir(src)
    for file in files:
        if os.path.isdir(os.path.join(src,file)): # 是文件夹吗?
            os.mkdir(os.path.join(target,file)) # 是文件夹先在target创建一个同名的文件夹
            copy(os.path.join(src,file),os.path.join(target,file)) # 递归
        else: # 不是文件夹正常传
            with open(os.path.join(src,file),'rb') as stream:
                container = stream.read()
                with open(os.path.join(target,file),'wb') as stream1:
                    stream1.write(container)
copy(src_path,target_path)
  • 老师写的能看懂,过。
  • 注意mode这个地方尽量多写rbwb

129.总结和图书管理

  • 总结
    os.path与os的总结,不再打一遍了,太多了。
  • 图书管理实战——理解持久化保存:放到文件中,但是以后查询的时候就更复杂,目前暂时使用文件。list、tuple、dict都不是持久的保存方式。老师是希望为以后的数据库学习打下基础。
    老师用了一个比较巧妙的方法进行文件中的用户和密码检索,就是利用字符串拼接后再与文件中的内容进行匹配。其他的内容没什么了,定义函数、while循环、for循环、文件io等。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值