Python Forum
Reading and writing Windows filepath without treating backslash as escape character
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Reading and writing Windows filepath without treating backslash as escape character
#1
I am writing a python script to sit between two Windows applications, one that generates a list of filenames, including the full path, and the other that requires a list of filenames, including the full path. How do I read from and write to text files that use vanilla Windows path names?

Thanks
Reply
#2
r in front of a string makes it interpret as a raw string
r'C:\User\UserName\'
or you can just escape it by doing
'C:\\User\\UserName\\'
Recommended Tutorials:
Reply
#3
But if I am reading from a file that only has single backslashes, how do I read the text as raw?
Reply
#4
When you get the path (bytes) from a file, the string is read as it is. There is no need to escape something which comes from outside. The representation of a string literal in program code is a different thing. In this case Python is interpreting the text. It allows shorthands like \0 \n \t for special characters or \x43 for hexadecimal.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How do I handle escape character in parameter arguments in Python? JKR 6 1,253 Sep-12-2023, 03:00 AM
Last Post: Apoed2023
  [SOLVED] [Windows] Fails reading strings with accents Winfried 1 859 Apr-23-2023, 05:27 PM
Last Post: Larz60+
  use of escape character in re.sub and find WJSwan 1 935 Feb-16-2023, 05:19 PM
Last Post: Larz60+
  Writing string to file results in one character per line RB76SFJPsJJDu3bMnwYM 4 1,410 Sep-27-2022, 01:38 PM
Last Post: buran
  change backslash into slash in a path paul18fr 7 2,463 Jul-21-2022, 04:26 PM
Last Post: deanhystad
  How to concatenate filepath with variable? Mark17 2 5,638 Jan-31-2022, 09:13 PM
Last Post: Mark17
  Escape indentation Frankduc 11 3,153 Jan-31-2022, 02:41 PM
Last Post: Frankduc
  add Escape charcters in string GrahamL 3 1,203 Jan-20-2022, 01:15 PM
Last Post: GrahamL
  Fastest Way of Writing/Reading Data JamesA 1 2,215 Jul-27-2021, 03:52 PM
Last Post: Larz60+
  [solved] unexpected character after line continuation character paul18fr 4 3,460 Jun-22-2021, 03:22 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020