'absolute file reference path not recognizing "\b" in subfolder "\bobby" of my file reference string as text
apologies if this has been asked before. I am currently learning to read/write to files using absolute referencing in Python. I am unfortunate enough to be named Bobby - meaning that my absolute reference for some files will be "C:\Users\bobby...", however it seems like the "\b" is changing the way that this is being read by Python. Again, I'm still learning, so I'm not sure how I would be able to reformat the string so that it accepts "\b" as an ACTUAL string. Would anyone be able to help me?
example inside of a class definition:
def get_high_score(self):
with open("C:\Users\bobby\Desktop\data.txt") as file:
contents = (file.read())
self.high_score = int(contents)
the contents of this file merely contain a single integer on the first line. Any help at all would be greatly appreciated!
Solution 1:[1]
Python (be default) uses \ to escape a character. This is used for writing newlines \n and more.
To make your string accept \ as it is, write it with a r preceding the string:
def get_high_score(self):
with open(r"C:\Users\bobby\Desktop\data.txt") as file: # Note the "r" before the string!
contents = (file.read())
self.high_score = int(contents)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Adid |
