Python 用连字符替换文件名中的空白
我使用下面的一行通过在名称末尾添加时间戳来重命名mp4文件Python 用连字符替换文件名中的空白,python,python-2.7,Python,Python 2.7,我使用下面的一行通过在名称末尾添加时间戳来重命名mp4文件 mediaName_ts = "%s_%s.mp4" %(pfile, time.strftime("%Y-%m-%d_%H:%M:%S", time.gmtime())) 但是,当文件名有空白时,我在访问文件时遇到问题: 名称文件test.mp4 如何删除空白,用连字符替换,并将时间戳附加到文件名的末尾 因此,文件名将是:name-file-test\u 2016-02-11\u 08:11:02.mp4 我已经做了时间戳部
mediaName_ts = "%s_%s.mp4" %(pfile, time.strftime("%Y-%m-%d_%H:%M:%S", time.gmtime()))
但是,当文件名有空白时,我在访问文件时遇到问题:
名称文件test.mp4
如何删除空白,用连字符替换,并将时间戳附加到文件名的末尾
因此,文件名将是:name-file-test\u 2016-02-11\u 08:11:02.mp4
我已经做了时间戳部分,但没有做空格。要用连字符替换空格,请使用内置方法:
要使用连字符替换空格,请使用内置方法: 您可以使用该方法或 小例子:
mystr = "this is string example....wow!!! this is really string"
print mystr.replace(" ", "_")
print re.sub(" ","_", mystr)
输出:
this_is_string_example....wow!!!_this_is_really_string
this_is_string_example....wow!!!_this_is_really_string
您可以使用该方法或
小例子:
mystr = "this is string example....wow!!! this is really string"
print mystr.replace(" ", "_")
print re.sub(" ","_", mystr)
输出:
this_is_string_example....wow!!!_this_is_really_string
this_is_string_example....wow!!!_this_is_really_string
以下操作应该有效,它使用
os.path
操作文件名:
import re
import os
import time
def timestamp_filename(filename):
name, ext = os.path.splitext(filename)
name = re.sub(r'[ ,]', '-', name) # add any whitespace characters here
return '{}_{}{}'.format(name, time.strftime("%Y-%m-%d_%H:%M:%S", time.gmtime()), ext)
print timestamp_filename("name file test.mp4")
这将显示:
name-file-test_2016-02-11_12:09:48.mp4
以下操作应该有效,它使用
os.path
操作文件名:
import re
import os
import time
def timestamp_filename(filename):
name, ext = os.path.splitext(filename)
name = re.sub(r'[ ,]', '-', name) # add any whitespace characters here
return '{}_{}{}'.format(name, time.strftime("%Y-%m-%d_%H:%M:%S", time.gmtime()), ext)
print timestamp_filename("name file test.mp4")
这将显示:
name-file-test_2016-02-11_12:09:48.mp4