【问题标题】:How to stop a \ from closing a string [duplicate]如何阻止\关闭字符串[重复]
【发布时间】:2015-12-10 21:42:29
【问题描述】:

我需要在文件夹中打开一个文件,这应该可以,但是 \ 会导致字符串关闭,因此当 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

【问题讨论】:

  • 在文件路径中使用正斜杠。它会让事情变得更容易。

标签: python file python-3.4 definition


【解决方案1】:

你需要转义反斜杠:

"Test\\"

或者干脆使用正斜杠"Test/"

您也可以让os.path.join 负责加入您的路径:

import os

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

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

我还建议使用with 打开你的文件,如果你想要一个行列表你可以调用readlines,如果你真的想删除换行你可以调用文件对象上的map 或使用一个列表比较:

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

或者:

     Door = [ln.rstrip() for ln in f]

【讨论】:

  • 原始字符串呢?
  • @PeterWood,在 OP 的情况下它实际上不起作用,你会得到一个 syntaxError。
猜你喜欢
  • 2012-05-14
  • 1970-01-01
  • 2019-10-10
  • 2019-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-05
  • 1970-01-01
相关资源
最近更新 更多