Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:如何替换文件名中的破折号?_Python_Recursion_Rename_Parsing - Fatal编程技术网

Python:如何替换文件名中的破折号?

Python:如何替换文件名中的破折号?,python,recursion,rename,parsing,Python,Recursion,Rename,Parsing,这个问题与递归重命名文件有关 更改为替换破折号的代码不适用于以下情况: ./Beginners Tools/Hello's -Trojans-/bif43243 ./Linux/Nux Col - 1 Works (TEX & Pdf) - T'eouhsoe & More (33323 - 34432) ./Git/peepcode-git-mov/c6_branch_merge.mov ./haskell/OS 2007 - T aoue ./B Sites for Get-

这个问题与递归重命名文件有关

更改为替换破折号的代码不适用于以下情况:

./Beginners Tools/Hello's -Trojans-/bif43243
./Linux/Nux Col - 1 Works (TEX & Pdf) - T'eouhsoe & More (33323 - 34432)
./Git/peepcode-git-mov/c6_branch_merge.mov
./haskell/OS 2007 - T aoue
./B Sites for Get-Big
./oeu'oeu - X ee ls - Feb 2008.pdf
它处理的案例包括:

./Beginners Tools/Hello's -Trojans-/bif43243
./Linux/Nux Col - 1 Works (TEX & Pdf) - T'eouhsoe & More (33323 - 34432)
./Git/peepcode-git-mov/c6_branch_merge.mov
./haskell/OS 2007 - T aoue
./B Sites for Get-Big
./oeu'oeu - X ee ls - Feb 2008.pdf
所以我需要解析数据。如何正确替换破折号

[详细信息]

代码来自链接,但更改为替换“-”:

Python并没有取代每一个破折号。我认为这是因为名字中包含了一些特殊的符号,使脚本停止了。所以我在归档时遇到了错误:

tar cvzf sed_backup.tar.gz `find documents | sed  s/\.*/\'\&\'/`
tar: rojans-: Cannot stat: No such file or directory
tar: Error is not recoverable: exiting now

由于名称中仍保留符号“'”和“-”,因此tar命令将“'”解释为find命令的结束,将“-”解释为路径中的选项符号“/初学者工具/Hello's-特洛伊木马-/bif43243”

os.path.walk便于遍历文件系统树,一个简单的示例:

import os, shutil

def rename_file(arg, dirname, filename):
   filepath = os.path.join(dirname, filename)
    # check if file meets your rename condition here
    if os.path.isfile(filepath):
       new_name = "something"
       shutil.move(filepath, os.path.join(dirname, new_name)

os.path.walk(base_dir, rename_file, None)
问候
Arthur很可能你的问题是单引号、括号和破折号。您可以逃避它们,也可以替换它们

实际上,查看您的编辑,您链接到的原始代码正在替换文件名中的字符,而不是整个路径。您需要转义路径中的字符:

esc_dirpath = dirpath.replace('-','\-') esc_dirpath=dirpath.replace('-','\-')) 这相当简单,还可以使用正则表达式对一组字符进行转义


我建议在您实际执行重命名之前,在转义/替换这些字符之前和之后运行os walk并打印出特殊情况

这篇文章可能会有所帮助:

您链接到的答案使用os.walk。因此,它是递归的。如果您发布了替换破折号的代码片段以及出现的错误,这会有所帮助。如果您使用的是Python 2.6或更高版本,则os.path.WACK因os.WACK的优点而被弃用;)