使用 python - regex 重命名文件

发布于 2024-09-28 13:02:43 字数 113 浏览 0 评论 0原文

我想使用 python 重命名 1k 文件。它们基本上都是 somejunkDATE.doc 格式

,我想删除所有垃圾,只留下日期。我不确定如何将其与目录中的所有文件相匹配。

谢谢

I am wanting to rename 1k files using python. they are all in the format somejunkDATE.doc

basically, I would like to delete all the junk, and only leave the date. I am unsure how to match this for all files in a directory.

thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

流云如水 2024-10-05 13:02:43

如果您的日期格式始终相同,则只需使用切片

>>> file="someJunk20101022.doc"
>>> file[-12:]
'20101022.doc'
>>> import os
>>> os.rename(file, file[-12:]

如果您想检查数字是否为有效日期,请将 file[-12:-3] 传递给 time 或要检查的 datetime 模块。

假设你的文件都在一个目录中(没有子目录)

import os
import glob
import datetime,time #as required
os.chdir("/mypath")
for files in glob.glob("*.doc"):
    newfilename = files[-12:]
    # here to check date if desired
    try:
       os.rename(files,newfilename)
    except OSError,e:
       print e
    else: print "ok"

If your date format is the same throughout, just use slicing

>>> file="someJunk20101022.doc"
>>> file[-12:]
'20101022.doc'
>>> import os
>>> os.rename(file, file[-12:]

If you want to check if the numbers are valid dates, pass file[-12:-3] to time or datetime module to check.

Say your files are all in a directory (no sub directories)

import os
import glob
import datetime,time #as required
os.chdir("/mypath")
for files in glob.glob("*.doc"):
    newfilename = files[-12:]
    # here to check date if desired
    try:
       os.rename(files,newfilename)
    except OSError,e:
       print e
    else: print "ok"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文