2

I am attempting to change the double forward slashes of the path seperators with single forward slashes. The program reads a text file with a list of files including paths. I am also using a windows box.

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))

With:

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

It works fine but not what I want.. But if I replace the forward slash with a backward slash, I get a syntax error

1 Answer 1

4

Backslash \ is an escape character that indicates that the character following it should be interpreted specially. Like \n for carriage return. If the character following the single backslash isn't a valid character for interpretation, it will error.

A backslash is a valid character for interpretation meaning a single backslash. So:

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

will replace a single backslash with a single forward slash. To convert a double backslash to a single backslash, use:

line = line.replace("\\\\", "\\")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.