【问题标题】: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)

谁能帮帮我?

【问题讨论】:

  • 使用f.read()将文件内容读入字符串。
  • 没关系,但尽量专注于比语法更清晰。
  • 我很高兴能改进我的语法。

标签: 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-13
      • 1970-01-01
      • 1970-01-01
      • 2017-03-08
      • 2021-02-23
      • 2017-12-24
      • 2018-08-04
      相关资源
      最近更新 更多