【问题标题】:Rename All Files in a Directory Using Python使用 Python 重命名目录中的所有文件
【发布时间】:2014-12-30 07:16:20
【问题描述】:

我有一个目录,其中包含许多具有这种格式的文件:

1 or 2 numbers_S followed by 1 or 2 numbers_L001_R1 or R2_001.fastq

Examples: 1_S1_L001_R1_001.fastq or 14_S14_L001_R2_001.fastq

我希望文件名是这样的:1_R1.fastq 14_R2.fastq

我已经找出了反映文件名的regexp,并且可以在TextWrangler 中成功地进行搜索和替换。下面是我想出的正则表达式:

Search: (\d+)\wS\d+\wL001\w(R\d)\w001(\.fastq)
Replace: \1_\2\3 (or $1_$2$3 depending on the program)

但是,我想知道如何使用简单的 Python 脚本批量重命名文件。如有任何建议,我将不胜感激。

谢谢!

【问题讨论】:

  • 您能告诉我们您当前尝试的代码吗?

标签: python regex rename batch-rename


【解决方案1】:

你可以这样做

 import glob, re, os

 for filename in glob.glob('/some/dir/*.fastq'):
     new_name = re.sub(pattern, r'\1_\2\3', filename)
     os.rename(filename, new_name)

【讨论】:

    【解决方案2】:

    考虑使用 os 包,您可以从中使用 os.rename(src, dst)。文档是正确的here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-16
      • 2014-06-05
      • 2015-02-28
      • 2014-11-08
      • 2014-10-09
      • 2013-08-20
      • 2014-11-29
      • 1970-01-01
      相关资源
      最近更新 更多