我试图用单个正斜杠更改路径分隔符的双正斜杠。该程序读取包含路径的文件列表的文本文件。我也在使用一个窗户盒。
f = open('C:/Users/visc/scratch/scratch_child/test.txt')
destination = ('C:/Users/visc')
# read input file line by line
for line in f:
line = line.replace("\\", "/")
#split the drive and path using os.path.splitdrive
(drive, path) = os.path.splitdrive(line)
#split the path and fliename using os.path.split
(path, filename) = os.path.split(path)
#print the stripped line
print line.strip()
#print the drive, path, and filename info
print('Drive is %s Path is %s and file is %s' % (drive, path, filename))
使用:
line = line.replace("\\", "/")
它工作正常,但不是我想要的..但如果我用反斜杠替换正斜杠,我会收到语法错误
答案 0 :(得分:2)
反斜杠\是一个转义字符,表示应该特别解释其后面的字符。喜欢\ n用于回车。如果单个反斜杠后面的字符不是解释的有效字符,则会出错。
反斜杠是解释的有效字符,表示单个反斜杠。所以:
line = line.replace("\\", "/")
将使用单个正斜杠替换单个反斜杠。要将双反斜杠转换为单个反斜杠,请使用:
line = line.replace("\\\\", "\\")