用连字符替换文件名中的空格

时间:2016-02-11 12:02:05

标签: python python-2.7

我使用以下行重命名mp4文件,方法是在名称的末尾添加一个时间戳。

    mediaName_ts = "%s_%s.mp4" %(pfile, time.strftime("%Y-%m-%d_%H:%M:%S", time.gmtime()))

但是当文件名有空格时,我在访问文件时遇到问题: name file test.mp4

如何删除空白区域,用连字符替换它并将时间戳添加到文件名的末尾?

因此文件名将为:name-file-test_2016-02-11_08:11:02.mp4

我已经完成了时间戳部分,但没有空格。

3 个答案:

答案 0 :(得分:5)

要使用连字符替换空格,请使用内置str.replace()方法:

string = "name file test"
print(string)
#name file test
string = string.replace(" ", "-")
#name-file-test

答案 1 :(得分:1)

以下内容应该有效,它使用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

答案 2 :(得分:0)

您可以使用str.replace()方法或re.sub()

小例子:

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
相关问题