英文:
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_fd
和 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
)
英文:
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
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论