基于文档文本字符串重命名多个文件

时间:2014-03-16 22:53:43

标签: python windows batch-file rename file-rename

我已经看到有一些叫做Bulk Rename Utility的东西,但我想重命名的数据文件是相对机密的,所以,也许是不合理的,我对使用它很谨慎。同样,我不确定它是否允许我在重命名文件时以我希望的方式寻找特定的字符串。因此,我想知道是否有一种替代方法几乎同样好,并且有一些方法可以确保一切都保密。如果没有,我会乐于听到任何人使用批量重命名实用程序的经历。谢谢!

编辑:我还应该注意,虽然我在编程方面是一个新手,但我对基于编程的解决方案非常开放。我还应该注意,所有相关文件都是 .html文件。

更新:

这样的事情会起作用吗?

 for file in directory:
 f = fopen(file, 'r')
 line = f.readLine();
 while(line):
  if(line.strip() == '<th style="width: 12em;">Name:</th>'):
   nextline = f.readLine().strip();
   c = nextline.find("</td>")
   name = nextline[4:c]
   os.commandline(rename file to name)
   break
  line = f.readLine()

在Python中运行良好是否有任何我缺失的东西?

更新:示例html

<html> <body>
   <h1 style="text-align: right;">[TITLE]</h1>
    <div style="font-size: 12pt;">
      <div style="float: left;">[NUMBER]</div>
      <div style="float: right;">[DATE]</div>
      <div style="clear: both;" />
    </div>
    <hr />
    <h3>[INFO]</h3>
    <table class="text" cellspacing="0" cellpadding="0" border="0">
      <tr>
        <th style="width: 12em;">Name:</th>
        <td>[NAME]</td>
      </tr> </body> </html>

2 个答案:

答案 0 :(得分:2)

不好意思,你的问题不够明确。在多次阅读您的问题后,我假设您需要一个方法(可能是Windows批处理.bat文件):

  • 允许用户输入搜索字符串。
  • 处理多个扩展名为.html的文件。
  • 在每个文件中查找搜索字符串第一次匹配后出现在下一行中的<td></td>标记之间的值,并使用它来重命名该文件。

下面的批处理文件执行以下过程:

@if (@CodeSection == @Batch) @then

@echo off

set /P "search=Enter search string: "
for /F "delims=" %%a in ('dir /B /A-D *.html') do (
   for /F "delims=" %%b in ('cscript //nologo //e:jscript "%~F0" "%%a"') do (
      if "%%b" neq "NoNameFound" (
         ECHO ren "%%a" "%%b"
      ) else (
         echo ERROR: No name found in file "%%a"
      )
   )
)
goto :EOF

@end

var file = new ActiveXObject("Scripting.FileSystemObject").OpenTextFile(WScript.Arguments.Item(0)),
    search = WScript.CreateObject("WScript.Shell").Environment("Process")("search"),
    re = new RegExp(search+".+\n.+<td>(.+)<\/td>",""), result;

if (result = re.exec(file.ReadAll())) {
   WScript.Stdout.WriteLine(result[1]);
} else {
   WScript.Stdout.WriteLine("NoNameFound");
}
file.Close();

这是您的示例数据的输出:

C:\> test
Enter search string: <th style="width: 12em;">Name:</th>
ren "input.html" "[NAME]"

请注意,此批处理文件只是显示 ren命令,但它不执行它!您需要在ECHO之前删除ren部分才能执行它。

如果我遗漏了某些内容,请输入评论,修改我的规格。

答案 1 :(得分:1)

使用powershell和cmd更改名称,就像老板一样,只需参考链接

http://www.howtogeek.com/111859/how-to-batch-rename-files-in-windows-4-ways-to-rename-multiple-files/

在阅读整页之前不要得出结论。