Python学习笔记七之文件操作:打开与写入、创建与删除、遍历文件夹批处理等

基本文件操作

1.文本文件:基于字符编码,存储的是普通字符串,不包括字体、字号、样式、颜色等信息,可通过文本编辑器显示和编辑,例如txt文件;
2.二进制文件:基于值编码的,以字节形式存储,其编码长度根据值的大小长度可变。通常在文件的头部相关属性中定义表示值的编码长度。例如视频、音频等。

1.创建和打开文件

在这里插入图片描述
在这里插入图片描述

open and close file

file=open(filename,mode)
file.close

#打开并写入命令
file=open('123.txt','w')

#打开格式及编码
file=open('1.png','rb')
file=open('notice.txt','r',encoding='utf-8')#打开以utf-8编码的文件

mode模式如下:
在这里插入图片描述
打开文件时使用with语句

打开文件后,要及时关闭,如果忘记关闭会带来问题,另外打开文件异常时,将会倒是文件不能被及时关闭
->使用with语句可以避免此问题发生,它将实现无论是否有异常,都可以在语句执行完毕后关闭打开的文件

with expression as target:
    with-body
#with-body指执行语句,如果不想执行,可以直接用pass代替
with open('message.txt','w') as file:
    pass

2.文件读写操作

在这里插入图片描述

#file.write
fp=open('test.txt','w',encoding='utf-8')
for i in range(1,11):
    fp.write('hello world!' +str(i) +'\n')
fp.close()
***
output:
hello world! 1
hello world! 2
hello world! 3
hello world! 4
hello world! 5
hello world! 6
hello world! 7
hello world! 8
hello world! 9
hello world! 10

*****写入一行******
lines=[]
for i in range(1,1):
    lines.append('hello world!' +str(i) +'\n')
with open('test.txt','w',encoding='utf-8') as fp:
    fp.writelines(lines)

*************************************
#file.read
with open('test.txt','r',encoding='utf-8') as fp:
    content=fp.read()#读取文件内容
    print(content)

***读取全部行***
with open('test.txt','r',encoding='utf-8') as fp:
    content=fp.readlines()#读取文件内容全部行
    print(content)
    
***读取一行***
with open('test.txt','r',encoding='utf-8') as fp:
   number=0
   while True:
       number+=1
       line=fp.readline()
       if line='':
           break
       print(number,line,end='\n')#输出每行内容

******文件复制***
with open('test.txt','r',encoding='utf-8') as fp:
    content=fp.read()
with open('test_2.txt','w',encoding='utf-8') as fp:
    fp.write(content)

*****将test_2.txt内容插入到test.txt文件最后*****
with open('test_2.txt','r',encoding='utf-8') as fp:
    content=fp.read()
with open('test.txt','r+',encoding='utf-8') as fp:
    fp.read()#读取内容,r+将指针移动到最后
    fp.write(content)
#或者
with open('test.txt','a',encoding='utf-8') as fp:#a以附加模式打开test.txt
    fp.write(content)

3.文件与文件夹操作

import os

在这里插入图片描述

3.1 相对路径与绝对路径

绝对路径指.py在电脑中的总路径,如:F:\program\python\code\project1\code1\test.py
相对路径是之相对于当前项目文件夹中的路径,即:code1\test.py或者 ./code/test.py

#相对路径
with open('demo/message.txt') as file:
    pass
#or
with open(r'demo/message.txt') as file:
    pass
    
#绝对路径
import os
print (os.path.abspath(r'demo/message.txt'))#获取绝对路径

#拼接路径,在join()函数中,如果出现多个路径,则以最后的路径为准
import os
print(os.path.join("E:\\code","E:\\python\\mr","Code","C:\\","demo"))
#output:              
"C\\demo"

3.2 文件操作

import os

os.rename('a.txt','b.txt')#重命名
os.remove('b.txt')#删除文件
os.mkdir('新建1.txt')
os.getcwd()#获取当前目录
os.chdir("../")# 改变默认路径
os.path.exists("c:\\demo")#判断路径是否存在,return False or True

******for example******
import os
path="c\\demo"
if not os.path.exists(path):#指定要创建的目录
    os.mkdir(path)
    print("目录创建成功")
else:
    print("该目录已经存在")

***
#如果指定的目录有多级,而且最后一级的上级目录中有不存在的,则抛出FileNotFoundError异常,并且目录创建
#不成功,可以编写递归函数调用os.mkdir()函数实现,具体代码如下:
import os
def mkkdir(path):
    if not os.path.isdir(path):   #判断是否为有效路径
        mkdir(od.path.split(path)[0])
    else:
        return
    os.mkdir(path)  #创建目录
mkdir("D:/mr/test/demo")
    
******删除目录******
import os
path="C:\\demo\\test\\dir\\mr"
if od.path.exists(path):
    os.rmdir(path)#删除目录
    print("目录删除成功!")
else:
    print("该目录不存在!")

****rmdir()只能删除空的目录,想要删除非空目录,需要使用python内置标准模块shutil的rmtree()***
import shutil
shutil.rmtree("C:\\demo\\test")

3.3 文件移动、复制(好用)

import shutil

shutil.copyfile("oldfile","newfile") #oldfile和newfile都只能是文件

shutil.copy("oldfile","newfile") #oldfile只能是文件夹,newfile可以是文件,也可以是目标目录

shutil.copytree(“olddir”,”newdir”) #olddir和newdir都只能是目录,且newdir必须不存在

shutil.move("oldpos","newpos")#将一个路径移动到另一个路径下

os.rmdir(“dir”) #只能删除空目录

shutil.rmtree(“dir”) #空目录、有内容的目录都可以删

4.遍历目录

使用os.walk来遍历文件夹及子文件夹下所有文件并得到路径。os.walk的完整定义形式如下:

import os
os.walk(top, topdown=True, onerror=None, followlinks=False)
***input***
①top:需要遍历目录的地址。
②topdown为True,则优先遍历top目录;为False则优先遍历top的子目录(默认为True)。
③onerror 需要一个 callable 对象,当walk需要异常时,会调用。
④followlinks为True,则会遍历目录下的快捷方式实际所指的目录(默认False)***output***
每次遍历的对象返回的都是一个三元组(root,dirs,files):
       ①root 所指的是当前正在遍历的这个文件夹的本身的地址|
       ②dirs 是一个列表,内容是该文件夹中所有的目录的名字(不包括子目录)
       ③files 是一个列表,内容是该文件夹中所有的文件的名字(不包括子目录)
       

例如现在有文件夹结构如下:

os_test(文件夹)
      A(文件夹)
           A1(文件夹)
                  1.txt
                  2.txt
           A2(文件夹)
                  3.txt
        B(文件夹)
           B1(文件夹)
                  4.txt
                  5.txt
           B2(文件夹)
                  6.txt

通过如下demo实现:

import os
 
for root,dirs,files in os.walk('F:\py_dada\os_test'):
    print(root)
    
***output***
F:python\os_test
F:python\os_test\A
F:python\os_test\A\A1
F:python\os_test\A\A2
F:python\os_test\B
F:python\os_test\B\B1
F:python\os_test\B\B2

for root,dirs,files in os.walk('F:\py_dada\os_test'):
   print(dirs,files)

***output***
['A','B'],                     []
['A1','A2','A3'],              []
[],                            ['1.txt','2.txt']
[],                            ['3.txt']
['B1','B2'],                   []
[],                            ['4.txt','5.txt']
[],                            ['6.txt']

获取多有子文件路径

import os

for root,dirs,files in os.walk('F:\\python\\os_test'):
    for name in dirs:#循环输出遍历到的子目录
        print(os.path.join(root,name))

***output***
F:python\os_test\A
F:python\os_test\A\A1
F:python\os_test\A\A2
F:python\os_test\B
F:python\os_test\B\B1
F:python\os_test\B\B2

for root,dirs,files in os.walk('F:\\python\\os_test'):
    for file in files: #循环输出遍历到的文件
        print(os.path.join(root,file))
        
***output***
F:python\os_test\A\A1\1.txt
F:python\os_test\A\A1\2.txt
F:python\os_test\A\A2\3.txt
F:python\os_test\B\B1\4.txt
F:python\os_test\B\B1\5.txt
F:python\os_test\B\B2\6.txt
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

明月醉窗台

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值