选择批处理文件中的数字部分以进行重命名。

huangapple go评论75阅读模式
英文:

Selecting the numerical part of batch files for renaming

问题

代码部分不需要翻译,只提供问题的回答:

问题:出现了文件找不到的错误,原因是什么?

回答:问题出现的原因是在代码中,os.listdir(path_video)返回的文件名只包含文件名本身,不包括路径信息。因此,当你尝试使用os.rename(filename, filename.replace('_pure_hm', ''))时,Python无法找到文件,因为它没有指定文件的完整路径。为了解决这个问题,你可以使用os.path.join将路径和文件名组合起来,像这样:

import os

path_initial = '/mnt'
path_video = os.path.join(path_initial, 'gazemap_videos')

for filename in os.listdir(path_video):
    old_path = os.path.join(path_video, filename)
    new_filename = filename.replace('_pure_hm', '')
    new_path = os.path.join(path_video, new_filename)
    os.rename(old_path, new_path)

这将为os.rename提供完整的文件路径,以便正确地找到和重命名文件。

英文:

In a directory, I have a folder with a lot of *.mp4 files that their names follow the pattern (num)_pure_hm.mp4. The numbers are not in order.

I need to rename them and in this regard by using the solution introduced here:

import os

path_initial = '/mnt'
path_video = os.path.join(path_initial,'gazemap_videos')

for filename in os.listdir(path_video):
    os.rename(filename, filename.replace('_pure_hm', ''))

Although I have a file with the name of 443_pure_hm.mp4 in that folder, I get the following error:

Exception has occurred: FileNotFoundError
[Errno 2] No such file or directory: '443_pure_hm.mp4' -> '443.mp4'
File "/home/Rename.py", line 7, in <module>
os.rename(filename, filename.replace('_pure_hm', ''))
FileNotFoundError: [Errno 2] No such file or directory:    '443_pure_hm.mp4' -> '443.mp4'

What is the problem?

答案1

得分: 3

os.listdir 只会列出文件名。你需要以某种方式添加路径。例如,使用 src_dir_fddst_dir_fd

import os

path_initial = '/mnt'
path_video = os.path.join(path_initial, 'gazemap_videos')

for filename in os.listdir(path_video):
    os.rename(
        filename, 
        filename.replace('_pure_hm', ''), 
        src_dir_fd=path_video, 
        dst_dir_fd=path_video
    )
英文:

os.listdir just lists the file names. You need to somehow add the path in. E.g. using src_dir_fd and dst_dir_fd:

import os

path_initial = '/mnt'
path_video = os.path.join(path_initial,'gazemap_videos')

for filename in os.listdir(path_video):
    os.rename(
        filename, 
        filename.replace('_pure_hm', ''), 
        src_dir_fd=path_video, 
        dst_dir_fd=path_video
    )

huangapple
  • 本文由 发表于 2023年3月9日 22:01:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75685647.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定