import re
b = open ('Filter_Lines.txt','w')
with open('Lines.txt') as f:
for trim in f:
repl = (re.sub('D:.*\\\\\\\\','',trim).rstrip('\n'))
b.write(repl + '\n')
b.close()
这是我从文本文件中删除目录路径的示例代码。 如果目录有" \\\"该代码正常工作。斜线。但不适用于" /////"。
我有一个包含以下这些行的文本文件。
1.large -if D:/Dolby_Harmanious_kit/Dolby_Atmos_for_Sound_Bar_Products_SIDK/Test_Materials/Test_Signals/upmix_multitone/upmix_multitone_c/truehd/upmix_multitone_c_6ch_to_8ch.mlp -of out_dut.wav
2.large -if D:/Dolby_Harmanious_kit/Dolby_Atmos_for_Sound_Bar_Products_SIDK/Test_Materials/Test_Signals/upmix_multitone/upmix_multitone_l/truehd/upmix_multitone_l_6ch_to_8ch.mlp -of out_dut.wav
3.large -if D:/Dolby_Harmanious_kit/Dolby_Atmos_for_Sound_Bar_Products_SIDK/Test_Materials/Test_Signals/upmix_multitone/upmix_multitone_lfe/truehd/upmix_multitone_lfe_6ch_to_8ch.mlp -of out_dut.wav
在此我需要删除路径
" d:/ Dolby_Harmanious_kit / Dolby_Atmos_for_Sound_Bar_Products_SIDK / Test_Materials / Test_Signals / upmix_multitone / upmix_multitone_c / TrueHD技术/"喜欢不同的路径线。你能指导我吗?
答案 0 :(得分:1)
import re
b = open ('Filter_Lines.txt','w')
with open('Lines.txt') as f:
for line in f:
repl = (re.sub('(D:.*\\\\)|(D:.*/)','',line).rstrip('\n'))
b.write(repl + '\n')
b.close()
据我所知,你需要windwos和linux路径,也许你的驱动器号会改变,所以你可以参数化它:
b = open ('Filter_Lines.txt','w')
DRIVE = "E:" #windows
with open('filetest') as f:
for trim in f:
repl = (re.sub('(' + DRIVE +'.*\\\\)|('+ DRIVE + '.*/)','',trim).rstrip('\n'))
b.write(repl + '\n')
b.close()
编辑 os.sep版本
import os
import re
b = open ('Filter_Lines.txt','w')
DRIVE = "E:" #windows
SEP = os.path.sep
if (SEP=="\\"):
SEP="\\\\"
with open('filetest') as f:
for line in f:
repl = (re.sub( DRIVE +'.*'+SEP,'',line))
b.write(repl)
b.close()