如何阻止\关闭字符串[复制](How to stop a \ from closing a string [duplicate])

编程入门 行业动态 更新时间:2024-10-22 13:57:40
如何阻止\关闭字符串[复制](How to stop a \ from closing a string [duplicate])

这个问题在这里已经有了答案:

在python中使用反斜杠(不要逃避) 2个答案

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

This question already has an answer here:

using backslash in python (not to escape) 2 answers

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

最满意答案

您需要转义反斜杠:

"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对象或者使用list comp:

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

要么:

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

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]

更多推荐

本文发布于:2023-08-01 16:44:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1361532.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   stop   closing   string   duplicate

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!