【问题标题】:struggling with os.rename() function挣扎于 os.rename() 函数
【发布时间】:2018-06-06 01:46:01
【问题描述】:

我正在尝试删除 python 3 中下载文件夹中每个文件的下划线,但我的程序最终出现错误

到目前为止,这是我的代码:

import shutil, os, re
for folder, downloads, songs in os.walk("C:/Users/TheTrojanHorse/Downloads"):
    print("the current folder is",folder)
    for song in songs:
        temp = song
        temp = (re.sub('[_]', ' ',temp))
        os.rename(song,temp)

这是错误:

os.rename(歌曲,临时) FileNotFoundError: [WinError 2] 系统找不到指定的文件

【问题讨论】:

  • 你的标题提到了os.rename,但你的代码只有os.remove。这是故意的吗?
  • @Kevin Ah 抱歉,这是我的旧代码,现在将更新
  • 这与您的问题无关,但您不需要使用正则表达式将一个字符串替换为另一个字符串。 temp.replace("_", " ") 也可以。

标签: python


【解决方案1】:

您需要指定song(可能还有temp)的完整路径,否则操作系统将在当前目录而不是C:/Users/TheTrojanHorse/Downloads 中查找文件:

os.rename(os.path.join(folder, song), os.path.join(folder, temp))

【讨论】:

  • 我已将其插入,但现在发生了这种情况:FileExistsError: [WinError 183] 当文件已存在时无法创建该文件。我不明白 os.rename() 将如何导致此错误发生@NPE
  • @TrojanHorse:例外情况正是它在锡上所说的。文档中甚至详细说明了这种行为(“在 Windows 上,如果 dst 已经存在,将引发 OSError...” - docs.python.org/2/library/os.html#os.rename
  • 请关注这个帖子stackoverflow.com/questions/51296315/renaming-images-in-folder/…。完整的文件路径是重命名文件的唯一方法。
猜你喜欢
  • 2021-08-05
  • 1970-01-01
  • 2023-04-06
  • 2014-08-30
  • 1970-01-01
  • 1970-01-01
  • 2015-08-24
  • 2012-01-06
  • 2012-12-29
相关资源
最近更新 更多