【问题标题】:Renaming Files Based on In-File Strings Using Python使用 Python 基于文件内字符串重命名文件
【发布时间】:2014-03-17 22:39:42
【问题描述】:

我在Windows and Rename tags 中发布了以下代码,并认为在这里询问此代码可能更有意义。本质上,我要做的是使用它根据文件中的特定文本字符串(下面的 line.strip() 中的文本字符串)重命名文件。我想知道如何在 Python 中实现类似的东西,因为这是我认为它应该看起来的粗略草图,但不是完整的作品。有没有最好的方法来填补这里的空白?任何建议将不胜感激。

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


    【解决方案1】:

    我认为移动文件最安全的方法是使用shutil module。为此,请替换替换

    os.commandline(rename file to name)
    

    shutil.move(os.path.join(directory,file), os.path.join(directory,name))
    

    【讨论】:

    • 谢谢,我试试看!
    【解决方案2】:

    您可以使用提供的os 命令重命名文件:(先关闭文件)

    f.close()
    os.rename(file_name, new_name)
    

    【讨论】:

    • 这很好,但它不适应我的需要,即根据我所知道的文件内文本字符串更改名称。
    • 看来您已经能够从上面提供的代码中获取文件名了。我认为这只是命名的问题。
    • 这能解决我在“os.commandline(rename file to name)”上遇到的语法错误吗?
    • 您完全不需要该行,因为 rename 可以解决这个问题。
    猜你喜欢
    • 1970-01-01
    • 2017-10-11
    • 2014-02-13
    • 1970-01-01
    • 2011-12-27
    • 2012-05-28
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多