You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python函数返回文件绝对路径变为脚本工作目录,求修正方案

修正文件重命名函数的绝对路径问题

问题场景

编写了用于重命名指定文件夹内文件并返回绝对路径的函数,但调用后发现返回的路径指向脚本工作目录,而非文件实际所在的原filepath目录,导致后续依赖正确路径的操作崩溃。原函数及调用代码如下:

原函数代码

import re
import os

# This function renames all files in a given
# folder and return them as absolute paths
def rename_get_Files(filepath):
    files = os.listdir(filepath)
    files_list = []
    counter = 1
    files_renamed = 0
    for filename in files:
        # If the file does not start with 'Offer_Pic_' > rename it and add to the files_list
        if not re.search('Offer_Pic_.+', filename):
            file_name, file_extension = os.path.splitext(filepath+filename)
            print(file_extension)

            new_filename = "Offer_Pic_" + str(counter) + file_extension
            old_filename = filepath + filename
            new_filename = filepath + new_filename
            # rename() function will
            # rename all the files
            os.rename(old_filename, new_filename)
            counter += 1
            print(f'This is the new filename: ' + new_filename)
            files_list.append(new_filename)
            files_renamed += 1
        else:
            # Append the absolute paths of all already correctly named files to the files_list
            files_list.append(os.path.abspath(filename))
    print(files_list)
    print(f'We have renamed ' + str(files_renamed) + ' files.')
    return files_list

调用代码

pictures = rename_get_Files(filepath)
print(pictures)

错误原因

  1. 路径拼接不规范:直接用filepath + filename拼接路径,在不同操作系统下可能出现分隔符问题,且容易出错。
  2. 已命名文件的路径生成错误:对于已符合命名规则的文件,os.path.abspath(filename)仅基于当前脚本工作目录生成路径,而非文件实际所在的filepath目录,导致路径指向错误。

修正后的代码

import re
import os

def rename_get_Files(filepath):
    files = os.listdir(filepath)
    files_list = []
    counter = 1
    files_renamed = 0
    # 用re.match匹配文件名开头,更精准
    pattern = re.compile(r'^Offer_Pic_.+')
    for filename in files:
        # 跳过文件夹,只处理文件
        file_full_path = os.path.join(filepath, filename)
        if os.path.isdir(file_full_path):
            continue
            
        if not pattern.match(filename):
            # 用os.path.splitext拆分文件名和后缀,基于完整路径
            _, file_extension = os.path.splitext(file_full_path)
            new_filename = f"Offer_Pic_{counter}{file_extension}"
            new_file_full_path = os.path.join(filepath, new_filename)
            os.rename(file_full_path, new_file_full_path)
            counter += 1
            print(f'This is the new filename: {new_file_full_path}')
            files_list.append(new_file_full_path)
            files_renamed += 1
        else:
            # 直接拼接原目录和文件名,得到正确的绝对路径
            files_list.append(file_full_path)
    print(files_list)
    print(f'We have renamed {files_renamed} files.')
    return files_list

关键修改点

  • 使用os.path.join()拼接路径,适配不同操作系统的路径分隔符,避免手动拼接的错误。
  • 对已符合命名规则的文件,直接通过os.path.join(filepath, filename)生成正确的绝对路径,替代错误的os.path.abspath(filename)。
  • 添加判断跳过文件夹,避免误操作目录。
  • 用re.match()替代re.search(),精准匹配文件名开头是否为Offer_Pic_。
  • 优化字符串格式化,使用f-string更简洁。

内容的提问来源于stack exchange,提问作者Jakob Czapski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 06:01:00