【问题标题】:How to create a variable with text file (Python 3.6)如何使用文本文件创建变量(Python 3.6)
【发布时间】:2018-02-28 12:13:46
【问题描述】:
我想为文本文件创建一个变量。我该怎么做?
例如:
with open("somefile.txt")as f:
defaVar = f
我想用它来将我的设置保存在我的程序中,例如:
password = input("some word...,hint:%d", f)
谁能帮帮我?
【问题讨论】:
标签:
python
python-3.x
file
text
【解决方案1】:
例如,如果somefile.txt 包含多行:
abc
def
ghi
你应该这样做:
with open('somefile.txt') as ff:
lines=ff.read().split('\n')
print(lines)
输出应该是:
['abc', 'def', 'ghi']
但如果你的文件只包含一行:
abc def ghi
你可以改用这个:
with open('somefile.txt') as ff:
lines=ff.read()
print(lines)
输出:
abc def ghi
【解决方案2】:
显然您只是想从文件中打印提示文本,请使用此代码-
with open("somefile.txt")as f:
defaVar = f.read()
password = input("blablabla...,hint: "+defaVar)