【问题标题】:i have an exported file that comes out with spaces, and i want to change that file to have hyphens我有一个带有空格的导出文件,我想将该文件更改为带有连字符
【发布时间】:2020-04-02 22:00:05
【问题描述】:

我当前的代码是:

import os

path  = os.getcwd()
filenames = os.listdir("C:/Users/Larso/Desktop/ClearEstimatesEstimate/")

filename = ('Leap Price Guide Export.xlsx')

for filename in filenames:
      os.rename(os.path.join(path, filename), os.path.join(path, filename.replace(' ', '-')))

for filename in filenames:
     os.rename(filename, filename.replace(" ", "-"))

但我得到错误

FileNotFoundError: [WinError 2] 系统找不到指定的文件:'C:\\Users\\larso\\Desktop\\ClearEstimatesEstimate\\AutomateExcelfileintoaspecficExcelfileformat\\AutomateExcelfileintoaspecficExcelfileformat' -> 'C:\\Users\\larso\\Desktop \\ClearEstimatesEstimate\\AutomateExcelfile 转换为specficExcel 文件格式\\AutomateExcelfile 转换为specficExcel 文件格式'

任何想法如何自动化

【问题讨论】:

  • 删除您的第一个 for 语句,其中您将使用您的文件名加入 CWD。​​span>
  • 我删除了 CWD 但仍然得到相同的结果
  • 您在第一个循环中重命名文件,因此在第一个循环后文件系统中不再存在带空格的文件。在第二个循环中,您仍然希望存在旧文件名(文件名中的文件名),从而导致错误。

标签: python


【解决方案1】:

只是一个疯狂的猜测:

有你的路径变量

path  = os.getcwd()

与您的文件名路径相同的路径

filenames = os.listdir("C:/Users/Larso/Desktop/ClearEstimatesEstimate/")

因为您将 path 变量中的路径与文件名变量中的 filename 组合在一起。

os.path.join(path, filename)

请打印两个路径值并比较它们的差异。或者更好地在您的 filenames 变量中使用您的 path 变量:

filenames = os.listdir(path)

【讨论】:

    【解决方案2】:

    os.getcwd() 将为您提供运行脚本的路径。

    os.listdir(path) 将为您提供路径目录中的文件名列表。

    所以你的工作目录中文件的绝对路径将是:

    os.getcwd() + '/' + filename
    

    试试这个,把你的脚本和你想重命名的文件放在同一个目录中。

    import os
    
    path  = os.getcwd()
    
    filenames = os.listdir(path)
    
    for filename in filenames:
          current_filename = path + '/' + filename
          os.rename(current_filename, current_filename.replace('_', ' '))
    

    【讨论】:

    • 所以路径不正确所以我尝试了 path =('C:/Users/Larso/Desktop/ClearEstimatesEstimate/Leap Price Guide Export.xlsx') #filename ('Leap Price Guide Export. xlsx') for filename in filenames: current_filename = path + '/' + filename os.rename(current_filename, current_filename.replace(' ', '_')) got error FileNotFoundError: [WinError 3] The system cannot find the path specified : 'C:/Users/Larso/Desktop/ClearEstimatesEstimate/Leap Price Guide Export.xlsx/.ipynb checkpoints' -> 'C:/Users/Larso/Desktop/ClearEstimatesEstimate/Leap_Price_Guide_Export.xlsx/.ipynb_checkpoints
    • print(path) 显示为 C:/Users/Larso/Desktop/ClearEstimatesEstimate/Leap Price Guide Export.xlsx 看起来是正确的导航
    • 如果将此脚本与要重命名的文件放在同一个文件夹中,则不必指定路径(并且可能会出错)。这不适合你吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-14
    • 2014-07-28
    • 1970-01-01
    相关资源
    最近更新 更多