Python 我有一个带空格的导出文件,我想将该文件更改为带连字符

Python 我有一个带空格的导出文件,我想将该文件更改为带连字符,python,Python,我目前的代码是: 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,

我目前的代码是:

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] The system cannot find the file specified: 'C:\\Users\\larso\\Desktop\\ClearEstimatesEstimate\\AutomateExcelfileintoaspecficExcelfileformat\\AutomateExcelfileintoaspecficExcelfileformat' -> 'C:\\Users\\larso\\Desktop\\ClearEstimatesEstimate\\AutomateExcelfileintoaspecficExcelfileformat\\AutomateExcelfileintoaspecficExcelfileformat' FileNotFoundError:[WinError 2]系统找不到指定的文件:“C:\\Users\\larso\\Desktop\\ClearEstimateStimate\\AutomateeXcelfinToAspeCficeXcelfFormat\\AutomateeXcelfinToAspeCficeXcelfFormat'->”C:\\Users\\larso\\Desktop\\ClearEstimateStimate\\AutomateeXcelfinToAspeCficexcelfFormat\\AutomateeXcelfinToAspeCficexcelfFormat” 任何关于如何实现自动化的想法

只是一个猜测:

有你的路径变量吗

path  = os.getcwd()
与文件名路径相同的路径

filenames = os.listdir("C:/Users/Larso/Desktop/ClearEstimatesEstimate/")
因为您将path变量中的路径与filename变量中的文件名组合在一起

os.path.join(path, filename)
请打印两个路径值并比较它们的差异。或者最好在文件名变量中使用path变量:

filenames = os.listdir(path)
os.getcwd()
将为您提供运行脚本的路径

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

因此,工作目录中文件的绝对路径为:

os.getcwd()+'/'+文件名
尝试此操作,脚本与要重命名的文件位于同一目录中

导入操作系统
path=os.getcwd()
filenames=os.listdir(路径)
对于文件名中的文件名:
当前文件名=路径+'/'+文件名
重命名(当前文件名,当前文件名.替换(“”,“”))

删除第一个for语句,在该语句中,您将使用文件名加入CWD。我删除了CWD,但仍然得到相同的结果您在第一个循环中重命名了文件,因此在第一个循环后,文件系统中不再存在带空格的文件。在第二个循环中,您仍然希望旧文件名(文件名中的文件名)出现,从而导致错误。因此路径不正确,所以我尝试了path=('C:/Users/Larso/Desktop/clearEstimateSimmate/Leap Price Guide Export.xlsx')#filename('Leap Price Guide Export.xlsx'))对于文件名中的文件名:current_filename=path+'/'+filename os.rename(current_filename,current_filename.replace('',''.')获取错误FileNotFoundError:[WinError 3]系统找不到指定的路径:“C:/Users/Larso/Desktop/ClearEstimateStimate/Leap Price Guide Export.xlsx/.ipynb checkpoints'->”C:/Users/Larso/Desktop/ClearEstimateStimate/Leap\u Price\u Guide\u Export.xlsx/.ipynb\u checkpoints(路径)显示为C:/Users/Larso/Desktop/ClearEstimateStimate/Leap Price Guide Export.xlsx,这看起来是到它的正确导航。如果将此脚本与要重命名的文件放在同一文件夹中,则无需指定路径(可能会出错)。这对你不管用吗?