我正在尝试同时拆分和剥离一根绳子。
我有一个文件 D:\printLogs\newPrintLogs\4.txt,我想将它拆分为只得到 4.txt 而不是剥离 .txt 并添加字符串 +“.zpr”以获得“4.zpr” .
这是我尝试使用的代码:
name = str(logfile)
print ("File name: " + name.split('\\')[-1] + name.strip( '.txt' ))
但是我得到了这个输出:
File name: 4.txtD:\printLogs\newPrintLogs\4
请您参考如下方法:
不要使用剥离和拆分。
首先,剥离会从集合中移除所有字符,您将移除所有't'、'x'和字符串开头和结尾的 '.' 个字符,无论顺序如何:
>>> 'tttx.foox'.strip('.txt')
'foo'
>>> 'tttx.foox'.strip('xt.')
'foo'
其次,Python 为您提供了 os.path module以跨平台和一致的方式处理路径:
basename = os.path.basename(logfile)
if basename.endswith('.txt'):
basename = os.path.splitext(basename)[0]
如果您只想删除任何扩展,您可以放弃str.endswith()测试:
basename = os.path.splitext(os.path.basename(logfile))[0]
演示:
>>> import os.path
>>> logfile = r'D:\printLogs\newPrintLogs\4.txt'
>>> os.path.splitext(os.path.basename(logfile))[0]
'4'
