使用模式重命名文件 [英] Rename a file with a pattern

查看:70
本文介绍了使用模式重命名文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像

的文件名

er-log-0.0.1-20150807.194034-8.jar

它遵循的格式就像

artifactId-version-timestamp.jar

我想将其重命名为 artifactId.jar.

我试过了

<预><代码>>>>fname = "er-log-0.0.1-20150807.194034-8.jar">>>导入操作系统>>>os.rename("er-log*", "er-log.jar")回溯(最近一次调用最后一次):文件<stdin>",第 1 行,位于 <module>OSError: [Errno 2] 没有那个文件或目录

文件在当前目录中

解决方案

您需要 glob 如果要使用 shell 通配符查找所有文件:

导入操作系统从 glob 导入 globpath = "/path_to_files"f = glob(os.path.join(path,"er-log*"))[0]os.rename(f, os.path.join(path,"er-log.jar"))

使用 "er-log*" 和 os.rename,python 正在寻找一个实际名为 "er-log*" 的文件.
如果在同目录下运行代码,则不需要加入路径,只需os.rename(f, "er-log.jar")

I have a filename that looks like

er-log-0.0.1-20150807.194034-8.jar

The format it follows is like

artifactId-version-timestamp.jar

I want to rename this to artifactId.jar.

I tried

>>> fname = "er-log-0.0.1-20150807.194034-8.jar"
>>> import os
>>> os.rename("er-log*", "er-log.jar")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 2] No such file or directory

The file is in the current directory though

解决方案

You need glob if you want to find all the files using a shell wildcard:

import os
from glob import glob
path = "/path_to_files"

f = glob(os.path.join(path,"er-log*"))[0]
os.rename(f, os.path.join(path,"er-log.jar"))

Using "er-log*" with os.rename, python is looking for a file actually called "er-log*".
If you run the code from the same directory, you don't need to join the path, just os.rename(f, "er-log.jar")

这篇关于使用模式重命名文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆