Jac*_*ins 1 python file definition python-3.4
我需要在一个文件夹中打开一个文件,这应该可以,但是\会导致字符串关闭,所以Me变量是绿色的,不应该是我.我该如何修复它,我需要能够阻止\关闭字符串或直接进入文件夹而不使用\符号.我使用的变量大多数似乎都是随机的,这是因为我不希望它与真正的函数类似,让它混淆了让我或其他人感到困惑.
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
Run Code Online (Sandbox Code Playgroud)
你需要逃避反斜杠:
"Test\\"
Run Code Online (Sandbox Code Playgroud)
或者只是使用正斜杠 "Test/"
你也os.path.join可以照顾你的路径:
import os
pth = os.path.join("Test", "{}.txt".format(Me))
with open(pth) as f:
Door = f.readlines()
Run Code Online (Sandbox Code Playgroud)
我还建议使用with打开文件,如果你想要一个可以调用的行列表readlines,如果你真的想要删除新行,你可以调用map文件对象或使用列表comp:
with open(pth) as f:
Door = list(map(str.rstrip, f))
Run Code Online (Sandbox Code Playgroud)
要么:
Door = [ln.rstrip() for ln in f]
Run Code Online (Sandbox Code Playgroud)