我的文件名看起来像
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"
>>> 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
该文件位于当前目录中
答案 0 :(得分:1)
如果要使用shell通配符找到所有文件,则需要glob:
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"))
将"er-log*"
与os.rename一起使用,python正在查找实际名为"er-log*"
的文件。
如果您从同一目录运行代码,则不需要加入路径,只需os.rename(f, "er-log.jar")
答案 1 :(得分:0)
// This slot is connected to QAbstractSocket::readyRead()
void SocketClass::readyReadSlot()
{
while (!socket.atEnd()) {
QByteArray data = socket.read(100);
file.write(data);
}
}
将c:\更改为您想要的路径:)
答案 2 :(得分:0)
以下是用户友好的方式实现目标的方法。
注意:
re
模块来确定传入的文件名是否与您的模式匹配,并提取文件名的根。典型用例:
# This one is particularly useful if the user has tab expansion
# in his shell. Tab expasion makes it easy to specify
# a single file name.
python rename_artifact.py er-log-0.0.1-20150807.194034-8.jar
# Or the user can glob the filename. "-n" and "-v" make it
# easy to see what the script would do/actually does.
python -n *.jar
python -v *.jar
代码:
import argparse
import re
import os
# Take a passed-in arg, confirm it matches
# the pattern, and add the new file name
def artifact(old_filename):
# Adjust regular expression to taste
result = re.match('(.*)-[0-9.]+-\d+\.\d+-\d+(\.jar)', old_filename)
if not result:
raise argparse.ArgumentTypeError(
"bad file name: {}".format(old_filename))
new_filename = ''.join(result.groups())
return old_filename, new_filename
parser = argparse.ArgumentParser(
description='Rename files to avoid timestamps')
parser.add_argument('-n', '--dry-run',
action='store_true',
help="Don't actually run any commands; just print them.")
parser.add_argument('-v', '--verbose',
action='store_true',
help='Verbosely list the files processed')
parser.add_argument(
'FILE',
help='File name, like er-log-0.0.1-20150807.194034-8.jar',
nargs='+',
type=artifact)
args = parser.parse_args()
for rename in args.FILE:
if args.dry_run or args.verbose:
print 'rename({},{})'.format(*rename)
if not args.dry_run:
os.rename(*rename)