3

I am trying to open a user's text file and replace a string in Python. I have the replacement working, but to open a file I understand that I need to add another backslash after each one in the file path. I am not sure how to do that. I looked at other stack overflow questions, but they were mostly about adding to the beginning or end of the string. Please help! Here's the code so far:

yourfile = input()

with open ("C:\\Users\\Rajrishi\\Documents\\MyJava\\text.txt") as myfile:
    data = myfile.readlines()
    strdata = "".join(data)
    strdata = strdata.replace("a string","a replacement")
    print(strdata)
1
  • Be aware that "C:\\text" means "a 7-character string, whose characters are a C followed by a colon, followed by a backslash, followed by text. Whereas "C:\text" means "a 6-character string, whose characters are a C followed by a colon, followed by a tab character, followed by ext. So there's no question of "adding another backslash to the string" -- the string only needs one backslash for each separator, and the issue is how to get a string that contains a backslash. Commented Sep 7, 2013 at 20:54

3 Answers 3

3

You may find it easier to pass a raw string by prefixing with r like so:

with open (r"C:\Users\Rajrishi\Documents\MyJava\text.txt") as myfile:

This will mean that you don't need to escape slashes

Sign up to request clarification or add additional context in comments.

Comments

3

You can actually use forward slashes:

with open("C:/Users/Rajrishi/Documents/MyJava/text.txt") as myfile:
    ...

Comments

0

If your code and your file in the same folder, you can do this :

with open (r"text.txt") as myfile:
    ...

Just write name of the file.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.