0

I need to open a file in a folder and this should work but the \ causes the string to close so the Me variable is green when it should not me. How can I fix it, I need to be able to stop \ from closing the string or direct into a folder without using the \ symbol. Most the variable I used seem random, this is because I do not want it to be similar to real functions to get it mixed up confusing me or others.

Me = Jacob #Variable me with Jacob in it
def God():#creates function called god
    File = open ("Test\" + Me + ".txt","r")#opens the Jacob file in the test folder.
    Door = ""#creates door variable
    Door = File.read().splitlines()#sets what is in Jacob file to be in Door variable
    print (Door)#prints the varible door
God()#does go function
Jacob cummins
  • 93
  • 1
  • 1
  • 8

1 Answers1

4

You need to escape the backslash:

"Test\\"

Or simply use a forward slash "Test/"

You can also let os.path.join take care of joining your path:

import os

pth = os.path.join("Test", "{}.txt".format(Me))

with open(pth) as f:
     Door = f.readlines()

I also recommend using with to open your files and if you want a list of lines you can call readlines, if you really want the newlines removed you can call map on the file object or use a list comp:

 with open(pth) as f:
     Door = list(map(str.rstrip, f))

Or:

     Door = [ln.rstrip() for ln in f]
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321