2016-02-11 44 views
0

我正在使用以下行通過向名稱的末尾添加時間戳來重命名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

我已經做了時間戳的一部分,但不是空白。

回答

5

對於帶連字符替換的空白,使用內建str.replace()方法:

string = "name file test" 
print(string) 
#name file test 
string = string.replace(" ", "-") 
#name-file-test 
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 
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