2

パスセパレータのダブルスラッシュをシングルスラッシュに変更しようとしています。プログラムは、パスを含むファイルのリストを含むテキストファイルを読み取ります。私もウィンドウズボックスを使用しています。

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("\\", "/")

正常に動作しますが、希望どおりではありません。ただし、スラッシュを円記号に置き換えると、構文エラーが発生します。

4

1 に答える 1

3

バックスラッシュ\は、それに続く文字を特別に解釈する必要があることを示すエスケープ文字です。キャリッジリターンの\nのように。単一の円記号に続く文字が解釈に有効な文字でない場合、エラーが発生します。

バックスラッシュは、単一のバックスラッシュを意味する解釈に有効な文字です。それで:

line = line.replace("\\", "/")

単一の円記号を単一のスラッシュに置き換えます。ダブルバックスラッシュをシングルバックスラッシュに変換するには、次を使用します。

line = line.replace("\\\\", "\\")
于 2012-05-09T23:09:28.410 に答える