【问题标题】:How can I change this script to also include a rename functionality?如何更改此脚本以包含重命名功能?
【发布时间】:2011-06-14 17:57:11
【问题描述】:

我有下面包含的当前脚本,该脚本进入扩展名为 .las 的文件并用其他字符串替换某些字符串(即:猫 -> 小猫,狗 -> 小狗)。

我想要的只是在这个脚本中添加一个功能,当我运行脚本时,它会将任何 .las 文件重命名为当前目录中的某个名称(即:*.las -> animals.las)。

我会将单个文件拖到此目录中,运行脚本,该脚本执行文本替换和重命名,然后将文件移出当前目录。所以对于这个脚本,我不在乎它会将多个 .las 文件重写为一个名称。

# read a text file, replace multiple words specified in a dictionary
# write the modified text back to a file

import re
import os
import time

# the dictionary has target_word:replacement_word pairs
word_dic = {
'cat' : 'kitten',
'dog' : 'puppy'
}


def replace_words(text, word_dic):
    """
    take a text and replace words that match a key in a dictionary with
    the associated value, return the changed text
    """
    rc = re.compile('|'.join(map(re.escape, word_dic)))
    def translate(match):
        return word_dic[match.group(0)]
    return rc.sub(translate, text)

def scanFiles(dir): 
    for root, dirs, files in os.walk(dir):
        for file in files:
            if '.las' in file:
            # read the file
                fin = open(file, "r")
                str2 = fin.read()
                fin.close()
            # call the function and get the changed text
                str3 = replace_words(str2, word_dic)
            # write changed text back out
                fout = open(file, "w")
                fout.write(str3)
                fout.close()
                #time.sleep(1)



scanFiles('')

我将在线示例中的脚本粘贴在一起,因此我不知道它的所有内部工作原理,因此如果有人有更优雅/有效的方式来执行此脚本正在执行的操作,我愿意更改它。

【问题讨论】:

  • 要将当前目录下的所有*.las文件重命名为animals.las?您是否打算最终得到多个具有相同名称的文件?这应该如何工作?
  • 正确。这将是一个工作目录,我在其中拖入一个 .las 文件,运行脚本,然后将字符串和文件名更正后的 .las 文件放回另一个目录。所以多文件问题不是问题。

标签: python wildcard rename


【解决方案1】:

如果你想得到一个包含 *.las 内容的名为 animals.las 的单个文件,那么你可以将 scanFiles 函数更改为在循环开始时打开 animals.las,写入每个文件的翻译输出*.las 文件到animals.las,然后关闭animals.las:

def scanFiles(dir): 
    fout = open("animals.las", "w")
    for root, dirs, files in os.walk(dir):
        for file in files:
            if '.las' in file:
            # read the file
                fin = open(file, "r")
                str2 = fin.read()
                fin.close()
            # call the function and get the changed text
                str3 = replace_words(str2, word_dic)
            # write changed text back out
                fout.write(str3)
                #time.sleep(1)
    fout.close()

【讨论】:

  • .las 文件中的单词替换已经开始工作。我无法将*.las 重命名为animals.las。在脚本运行之前,animals.las 不存在,只有一个随机的*.las 文件存在。正如我上面提到的,我知道这会将目录中的任何.las 重命名为animals.las。这对我来说完全没问题
  • 好的,我很抱歉,cnauroth。实际上,您通过动态创建一个新文件来解决这个问题(我对这一切都很陌生,所以我不明白那部分)。我在我的代码中输入了您的更正,除了将原始的*.las 文件写入animals.las 文件两次之外,它仍然有效。关于如何修复它的任何想法?哦!它遍历新创建的animals.las,因此文件被写入两次。不过,我如何才能让这个迭代只进行一次?
猜你喜欢
  • 2021-06-03
  • 2019-06-06
  • 1970-01-01
  • 1970-01-01
  • 2016-10-23
  • 2023-03-20
  • 2014-07-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多