如何在ipython中将目录中的空格替换为下划线?

-3 投票
2 回答
790 浏览
提问于 2025-04-19 04:52

有时候,把空格换成下划线是很有用的。在Linux机器上,这对我来说没问题:

find /tmp/ -depth -name "* *" -execdir rename 's/ /_/g' "{}" \;

在Windows上,我想用ipython来实现这个功能。我觉得很多人可能遇到过这个问题,你们是怎么在ipython中实现的呢?

谢谢大家!

编辑:
抱歉之前的误解。这里是我的脚本:

import os

def rm_space():
    for filename in os.listdir("."):
        if filename.find(" ") > 0:
            newfilename = filename.replace(" ", "_")
            os.rename(filename, newfilename)

这段代码确实可以把空格换成下划线;不过,有个问题:怎么才能递归地替换呢?

我觉得这是个很常见的问题,可能已经有一种很自然的方式来解决它,就像上面的shell脚本一样。

2 个回答

0

如何进行递归替换?

使用 OS.walk() 而不是 listdir。

1

从StackOverflow上复制的代码并进行了编辑,在我的Mac上可以正常运行。

import os
import sys

directory = sys.argv[1] # parse through file list in the current directory

for filename in os.listdir(directory): # parse through file list in the current directory

    if filename.find(" ") > 0: # if an space is found

        newfilename = filename.replace(" ","_") # convert underscores to space's

        old_file_path = os.path.join(directory, filename) 
        new_file_path = os.path.join(directory, newfilename)

        os.rename(old_file_path, new_file_path) # rename the file, note that arg[] of os.rename is path_of_file, that explains 2 lines of code above    

撰写回答