Python:读取字符串并使用它来重命名文件

时间:2018-09-06 08:37:34

标签: python-3.x os.path

我是python的新手,我正在尝试使用文件内特定行上的字符串来重命名一组文件,并使用它来重命名文件。在每个文件的同一行都可以找到这样的字符串。

例如:

  • 相同路径中的10个文件
  • 该字符串位于第14行,起始于字符号40,长度为50个字符
  • 然后使用提取的字符串重命名相应的文件

我正在尝试使用此代码,但无法弄清楚如何使其工作:

for filename in os.listdir(path):
  if filename.startswith("out"):
     with open(filename) as openfile:
        fourteenline = linecache.getline(path, 14)
           os.rename(filename, fourteenline.strip())

1 个答案:

答案 0 :(得分:1)

请谨慎提供文件的完整路径,以防您尚未在该文件夹中工作(请使用os.path.join())。此外,使用线缓存时,您无需open文件。

import os, linecache

for filename in os.listdir(path):
    if not filename.startswith("out"): continue # less deep
    file_path = os.path.join(path, filename) # folderpath + filename
    fourteenline = linecache.getline(file_path, 14) # maybe 13 for 0-based index?
    new_file_name = fourteenline[40:40+50].rstrip() # staring at 40 with length of 50
    os.rename(file_path, os.path.join(path, new_file_name))

有用的资源: