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

2024-09-30 14:17:54 发布

您现在位置: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, 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'

有没有想过如何实现自动化


Tags: path代码inforosfilenameusersreplace
2条回答

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

os.listdir(path)将为您提供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  = os.getcwd()

与文件名路径相同的路径

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

因为您将来自path变量的路径与来自filenames变量的filename组合在一起

os.path.join(path, filename)

请打印两个路径值并比较它们的差异。或者最好在文件名变量中使用路径变量:

filenames = os.listdir(path)

相关问题 更多 >