python文件处理操作

这篇博客介绍了Python中关于文件处理的各种操作,包括复制文件和文件夹、删除文件、判断目录是否存在、创建文件目录、列举目录下所有文件、使用mmap获取文件行数、获取文件最后一行、重命名文件等实用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.复制文件或者文件夹

  • 复制某个目录下面的文件到另一个目录下面。

        源文件和目标文件都只能是文件,且目标文件必须存在(open file not mknod),且有权限写入:shutil.copyfile(source_file_path,target_file_path)

def copy_file_cp_unix():
    source_path = 'source_file/test.py'
    source_path=os.path.join(os.getcwd(),source_path)

    target=os.path.join(os.getcwd(),"target_file")
    target=os.path.join(target,os.path.basename(source_path))
    print(target)

    # create the folders if not already exists
    if not os.path.exists(target):
        #MacOS需要超级用户权限才能运行mknod。如果您不想升级权限来创建文件,可以改为这样做
        open(target, 'w').close()

    # adding exception handling
    try:
        shutil.copyfile(source_path, target)
    except IOError as e:
        print("Unable to copy file. %s" % e)
    except:
        print("Unexpected error:", sys.exc_info())
  • 复制文件夹到某个目录下面

        复制某个文件夹到另一个目录下面,复制后的结果目录为“目录/某个文件夹“,注意这个复制后的结果目录在复制前必须是不存在的。

def copy_files():
    source_base_name = 'source_file'
    source_dir = os.path.join(os.getcwd(), source_base_name)

    target_dir = os.path.join(os.getcwd(), "target_file_path")
    target_dir=os.path.join(target_dir,source_base_name)

    # 如果目录存在,删除单层目录。
    if os.path.exists(target_dir):
        os.rmdir(target_dir)

    # adding exception handling
    try:
        shutil.copytree(source_dir, target_dir)
    except IOError as e:
        print("Unable to copy file. %s" % e)
    except:
        print("Unexpected error:", sys.exc_info())

2.删除文件和强制删除有内容的文件

remove(path)
#删除文件

rmdir(path)
#删除单层目录,如该目录非空则抛出异常

removedirs(path)
#递归删除目录,从子目录到父目录逐层尝试删除,遇到目录非空则抛出异常
def delete_files():
    source_base_name = 'source_file'
    target_dir = os.path.join(os.getcwd(), "target_file_path")
    target_dir = os.path.join(target_dir, source_base_name)

    if os.path.exists(target_dir):
        shutil.rmtree(target_dir)

3.判断目录是否存在

def file_exists(target_file_or_dir):
    if os.path.exists(target_file_or_dir):
        return True
    return False

4.创建文件目录

mkdir(path)
创建单层目录,如该目录已存在抛出异常

makedirs(path)
递归创建多层目录,如该目录已存在抛出异常,注意:'E:\a\b’和’E:\a\c’并不会冲突
创建的目录

5.打印某个目录下面的所有文件

os.listdir(path)返回的是一个包含该目录下面的所有文件的文件名的字符串的列表。

#获取一个目录下所有文件的个数
allFileNum = 0
def printPath(level, path):
    global allFileNum
    '''
    打印一个目录下的所有文件夹和文件
    '''
    # 所有文件夹,第一个字段是次目录的级别
    dirList = []
    # 所有文件
    fileList = []

    # 返回一个列表,其中包含在目录条目的名称(google翻译)
    files = os.listdir(path)

    # 先添加目录级别
    dirList.append(str(level))
    for f in files:
        if(os.path.isdir(path + '/' + f)):
            # 排除隐藏文件夹。因为隐藏文件夹过多
            if(f[0] == '.'):
                pass
            else:
                # 添加非隐藏文件夹
                dirList.append(f)
        if(os.path.isfile(path + '/' + f)):
            # 添加文件
            fileList.append(f)
            # 当一个标志使用,文件夹列表第一个级别不打印
            i_dl = 0
    for dl in dirList:
        if(i_dl == 0):
            i_dl = i_dl + 1
        else:
            # 打印至控制台,不是第一个的目录
            print('-' * (int(dirList[0])), dl)
            # 打印目录下的所有文件夹和文件,目录级别+1
            printPath((int(dirList[0]) + 1), path + '/' + dl)
    for fl in fileList:
        # 打印文件
        print('-' * (int(dirList[0])), fl)
    # 随便计算一下有多少个文件
    allFileNum = allFileNum + 1

6.借助mmap映射快速获取某个文件的所有行数

def get_file_row_count_mmap(dataPath):
    start = time.time()
    with open(dataPath, "r") as f:
        # memory-map the file, size 0 means whole file
        map = mmap.mmap(f.fileno(), length=0, access=mmap.ACCESS_READ)
        count = 0
        while map.readline():
            count += 1
        print(count)
        map.close()
    print(time.time() - start)
    #https: // blog.youkuaiyun.com / weixin_36060412 / article / details / 112521082

    return count

7.获取某一个文件的最后一行

# 文件已经生成后,取得文件的最后一行。
def get_last_row(self, file_name):
    with open(file_name, 'rb') as f:  # 打开文件
        # 在文本文件中,没有使用b模式选项打开的文件,只允许从文件头开始,只能seek(offset,0)
        first_line = f.readline()  # 取第一行
        offset = -50  # 设置偏移量
        while True:
            """
            file.seek(off, whence=0):从文件中移动off个操作标记(文件指针),正往结束方向移动,负往开始方向移动。
            如果设定了whence参数,就以whence设定的起始位为准,0代表从头开始,1代表当前位置,2代表文件最末尾位置。 
            """
            f.seek(offset, 2)  # seek(offset, 2)表示文件指针:从文件末尾(2)开始向前50个字符(-50)
            lines = f.readlines()  # 读取文件指针范围内所有行
            if len(lines) >= 2:  # 判断是否最后至少有两行,这样保证了最后一行是完整的
                last_line = lines[-1]  # 取最后一行
                break
                # 如果off为50时得到的readlines只有一行内容,那么不能保证最后一行是完整的
                # 所以off翻倍重新运行,直到readlines不止一行
                offset *= 2
                print('文件' + file_name + '第一行为:' + first_line.decode())
                print('文件' + file_name + '最后一行为:' + last_line.decode())

    return last_line.decode()

8.重命名文件

def rename_file(old, new):
    os.rename(old, new)

9.其余链接

python读写、创建文件、文件夹等等_python学习者的博客-优快云博客_python 新建文件夹

学习笔记、os模块函数、exists、isabs、isdir、islink、samefile_iken_g的博客-优快云博客

用Python复制文件的9个方法(转) - keeptg - 博客园

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值