【python】:文件读写操作及os常用功能

1.打开文件

file = open(filename,‘rb’)

【打开文件】
open() 函数

  • 常用格式 :open(file, mode=‘r’)
    https://docs.python.org/3/library/functions.html
    这里有所有python内建的函数及描述文档
    eg1:
f = open("d:/1.txt", 'w')
f.write("hello python")
f.close()

上面的代码以w(写)的方式打开文件d:/1.txt,然后写入 hello python, 最后关闭文件。运行程序后,找到d:/1.txt文件并打开,发现里面的内容是 hello python, 说明程序运行成功

eg2:

f = open('d:/1.txt', 'r')
msg = f.read()
f.close()
print(msg)

运行结果:
hello python
以 r (只读)方式打开文件,然后读取文件内容,再输出文件内容,即输出前面写入的 hello python

eg3:
打开文件写入多行内容

f = open("d:/2.txt", 'r')
lines = f.readlines()
f.close()
print(type(lines))
for line in lines:
    print(line.strip())

运行程序,显示结果:
<class ‘list’>
hello python1
hello python2
hello python3
hello python4
hello python5
hello python6
hello python7
hello python8
hello python9
hello python10
可见readlines()方法返回一个list对象

eg4:

f = open("d:/2.txt", 'r')
line = f.readline()
while line:
    print(line.strip())
    line = f.readline()
f.close()

运行程序,显示结果:
hello python1
hello python2
hello python3
hello python4
hello python5
hello python6
hello python7
hello python8
hello python9
hello python10

readline()方法一次只读取一行
read()方法返回文件全部内容,readlines()方法以列表的形式返回文件全部内容

f = open("d:/2.txt", 'a')
f.write('这行是追加的')
f.close()

以 a 方式打开文件,写入的内容将追加到最后。运行上面的代码发现确实追加了内容到最后

关键字with 在不再需要访问文件后将其关闭, python会保证with代码段内的文件对象自动关闭

with open("d:/3.txt", 'w') as f:
    f.write('写入文件的内容')
#打开excel文件
workbook = xlrd.open_workbook(filename)

#获取sheet
sheet = workbook.sheet_by_name(sheetname)

2.os文件操作

常用OS函数

os.access(path, mode)
检验权限模式	
os.getcwd()
返回当前工作目录
os.remove(path)
删除路径为path的文件。如果path 是一个文件夹,将抛出OSError; 查看下面的rmdir()删除一个 directory。
os.removedirs(path)
递归删除目录。
os.rename(src, dst)
重命名文件或目录,从 src 到 dst
os.renames(old, new)
递归地对目录进行更名,也可以对文件进行更名。

2.1 获取文件名

import os
path = os.getcwd() # 获取程序所在文件夹路径
print('程序所在文件夹路径是:'+path)

files = os.listdir(path) # 获取指定路径下的所有文件的文件名称
for file in files:
    if file.split('.')[-1] in ['txt']:
        print('这是一个文本文件:' + file)
    elif file.split('.')[-1] in ['doc','docx']:
        print('这是一个Word文件:' + file)
    elif file.split('.')[-1] in ['xls','xlsx']:
        print('这是一个Excel文件:' + file)
        

os+global 获取文件名

import glob
import os
files = glob.glob(os.path.join(path,'*.txt') # 匹配以'*.txt'为后缀的所有文件的全路径
for file in files:
    print(file)

os.path.isfile():判断某一对象(需提供绝对路径)是否为文件
os.path.isdir():判断某一对象(需提供绝对路径)是否为目录

import os

path = "D:/Qt_ui/"
# 创建两个列表,一个用来存储文件,一个用来存储文件夹
L_file = []
L_dir = []

for i in os.listdir(path):
    new_path = path + i   # 拼接后路径new_path
    if os.path.isfile(new_path):   # 判断是不是文件
        L_file.append(i)
    elif os.path.isdir(new_path):   # 判断是不是文件夹
        L_dir.append(i)

print("文件夹如下:")
for i in L_dir:
    print(i)

print("\n文件如下:")
for i in L_file:
    print(i)

2.2 删除文件夹

    img_folder = os.getcwd()
    file_list = []
    img_folder = r'C:\\Users\\Administrator\\Desktop\\test\\'
    # for file_name in os.listdir(img_folder):
    file_name = os.listdir(img_folder)[0]
    if os.path.isfile(img_folder + file_name):
        print("当前文件是文件", file_name)
    elif os.path.isdir(img_folder + file_name):
        print("当前文件是文件夹", file_name)
        # 直接开始删除操作
        # 获取的年级目录
        print("当前月文件为:", os.listdir(img_folder + file_name)[0])
        # 说明  linux 系统需要使用sorted()对os.listdir()结果进行排序,否则乱序
        print("当前日文件为:", os.listdir(img_folder + file_name + '\\' + str(os.listdir(img_folder + file_name)[0]))[0])
        # 删除日期最早的文件夹
        delete_file = img_folder + file_name + '\\' \
                      + str(os.listdir(img_folder + file_name)[0]) + '\\' \
                      + str(os.listdir(img_folder + file_name + '\\' + str(os.listdir(img_folder + file_name)[0]))[0])
        # 删除时间最早的文件夹(从天开始)
        os.removedirs(delete_file)
        # file_list.append(file_name)
   

eg:
windows:
delete_file C:/Users/Administrator/Desktop/test/img/2023/05/1
说明:
文件夹下有“ng ” “ok
linux下报错 ”两个文件夹
Windows下正常删除
报错OSError: [Errno 39]

delete_file 对应windows delete_file C:/Users/Administrator/Desktop/test/img/2023/05/1
   os.removedirs(delete_file)
  File "/usr/lib/python3.9/os.py", line 243, in removedirs
    rmdir(name)
OSError: [Errno 39] Directory not empty: '/home/pi/Desktop/test_init1/img/2023/05/1'

解决方式:
os.removedirs() 方法用于递归删除目录。像rmdir(), 如果子文件夹成功删除, removedirs()才尝试它们的父文件夹,直到抛出一个error(它基本上被忽略,因为它一般意味着你文件夹不为空)。
例如:
文件结构如下:

F:

\ a                                                        (代表F 目录下有一个文件夹a )

\ b, b.txt                                               (代表a 目录下有一个文件夹b 和 一个文本文件b.txt)

\ c                                                       (代表b 目录下有一个文件夹c )

\ d                                                       (代表c 目录下有一个文件夹d)

\ e                                                       (代表d 目录下有一个文件夹e )

\ f                                                        (代表e  目录下有一个文件夹f )

a目录下包含一个b目录和一个文件, b目录以下就是空目录套空目录了
如果我们执行
os.removedirs(r’F:\a\b\c\d\e\f’)
那么在函数的内部:
它依次删除了目录f, e, d, c,b 。每次删除一个目录时,**被删除的目录都是个空目录。**删除动作直到遇到一个非空目录a后才停下了。(因为目录a内还有文件b.txt)
所以结果为:
F:
\ a (代表F 目录下有一个文件夹a )
\ b

至于文章开通的例子为什么会报错,答案已经公布了,因为:该函数的工作方式像rmdir()一样,它删除多个文件夹的方式是通过在目录上由深及浅逐层调用rmdir()函数实现的。如果最深层的目录根本就不是空目录,所以会报错终止。

解决方案:

import shutil
shutil.rmtree(path, ignore_errors=True)

原文链接:https://blog.csdn.net/T704379675/article/details/55026009

2.2.1 os.removedirs() 和shutil.rmtree()的区别

shutil.rmtree() 表示递归删除文件夹下的所有子文件夹和子文件。

def rmtree(path, ignore_errors=False, onerror=None):
    """Recursively delete a directory tree. 递归删除目录树。

    If ignore_errors is set, errors are ignored; otherwise, if onerror
    is set, it is called to handle the error with arguments (func,
    path, exc_info) where func is platform and implementation dependent;
    path is the argument to that function that caused it to fail; and
    exc_info is a tuple returned by sys.exc_info().  If ignore_errors
    is false and onerror is None, an exception is raised.

	如果设置了ignore_errors,错误将被忽略; 
	否则,如果设置了onerror,则调用该函数以使用参数(func,path,exc_info)来处理错误,其中func与平台和实现有关; 
	path是导致该函数失败的参数。 而exc_info是sys.exc_info()返回的元组。 
	如果ignore_errors为false,onerror为None,则会引发异常。

    """

shutil.rmtree('E:\\myPython\\image-filter\\test', ignore_errors=True)

这样 test 文件夹内的所有文件(包括 test 本身)都会被删除,并且忽略错误。

shutil.copyfile( src, dst)   #从源src复制到dst中去。 如果当前的dst已存在的话就会被覆盖掉
shutil.move( src, dst)  #移动文件或重命名
shutil.copymode( src, dst) #只是会复制其权限其他的东西是不会被复制的
shutil.copystat( src, dst) #复制权限、最后访问时间、最后修改时间
shutil.copy( src, dst)  #复制一个文件到一个文件或一个目录
shutil.copy2( src, dst)  #在copy上的基础上再复制文件最后访问时间与修改时间也复制过来了,类似于cp –p的东西
shutil.copy2( src, dst)  #如果两个位置的文件系统是一样的话相当于是rename操作,只是改名;如果是不在相同的文件系统的话就是做move操作
shutil.copytree( olddir, newdir, True/Flase) #把olddir拷贝一份newdir,如果第3个参数是True,则复制目录时将保持文件夹下的符号连接,如果第3个参数是False,则将在复制的目录下生成物理副本来替代符号连接
shutil.rmtree( src )   #递归删除一个目录以及目录内的所有内容

removedirs()

def removedirs(name):
    """removedirs(name)

    Super-rmdir; remove a leaf directory and all empty intermediate
    ones.  Works like rmdir except that, if the leaf directory is
    successfully removed, directories corresponding to rightmost path
    segments will be pruned away until either the whole path is
    consumed or an error occurs.  Errors during this latter phase are
    ignored -- they generally mean that a directory was not empty.

	超级rmdir; 删除叶子目录和所有空的中间目录。 
	类似于rmdir的工作方式,不同之处在于,如果成功删除了叶目录,将删除最右边路径段所对应的目录,
	直到使用完整个路径或发生错误为止。 在后面的阶段中的错误将被忽略-它们通常意味着目录不是空的。

    """

os.removedirs()只能删除子文件夹中的空文件夹,非空无法删除

3.shutil 操作

python 中使用 shutil 实现文件或目录的复制、删除、移动

4.其他操作方式

3.1 新建txt文档

 with open("C:/Users/Administrator/Desktop/test/test.txt", "w") as f:
        f.write("test")

3.2 新建log文档

logging.basicConfig(filename=img_folder + 'test.log', level=logging.DEBUG)
logging.info('test')
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

时间之里

好东西就应该拿出来大家共享

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

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

打赏作者

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

抵扣说明:

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

余额充值