【问题标题】:Write a variable to a file in Python在 Python 中将变量写入文件
【发布时间】:2021-03-12 04:24:28
【问题描述】:

假设我有一个 python 函数,它从用户那里输入姓名、年龄、性别等,我有一个模板,我可以从中阅读并编写。例如,我有以下输入:

Name: Ashish
Age: 22
Gender: Male
Profession: Software Engineer

我有一个包含多行格式的模板:

Hi, Name
Your age is Age and you are Gender working as a Profession.....

我想从模板中读取并写入一个新文件并将变量动态添加到输出文件中而不使用替换功能是否可以像这样获得输出(例如):

Hi, Ashish
Your age is 22 and you are Male working as a Software Engineer.....

我不想使用替换功能,但想从模板文件中读取并将变量动态写入输出文件。帮助将不胜感激。我正在处理需要从文件中读取的自动化任务。这只是一个例子:)

【问题讨论】:

  • 您在为哪一部分苦苦挣扎?文件读取?文件写入?给变量赋值?这个问题有点宽泛。这是一个家庭作业问题,而不是 SO 的目的。如果您尝试一下但仍然有问题,那么这里就是您要来的地方。向我们展示一个诚实的尝试,最好是 minimal reproducible example,我们将很乐意提供帮助。
  • 从 Python 教程开始学习如何编写函数定义。

标签: python templates file-handling memory-efficient


【解决方案1】:
def write_to_file(name,age,gender,profession):
     message = "Hi {} \nYour age is {} and you are {} working as a 
           {}".format(name,age,gender,profession)
     return message

line = write_to_file("Janvi",20,"female","teacher")
my_file = open("file.txt","w")
my_file.writelines(line)

【讨论】:

  • 嗨,Pooja,只是一个小改动。当使用多行时(在变量消息中传递),最好使用三个双引号。
【解决方案2】:

假设您可以修改模板文件,您可以在模板文件作为字符串加载后使用 .format()。

def template_values(name, age, gender, profession):
    return "Hi {name}, Your age is {age} and you are {gender} working as a {profession}.....".format(
        name=name,
        age=age,
        gender=gender,
        profession=profession
    )

【讨论】:

  • 我正在从文件中读取模板,我不想复制整个文本并将其写入返回
  • 您可以在文件本身中使用 {variable} 格式,然后将其作为字符串读入。它仍然可以工作。
猜你喜欢
  • 1970-01-01
  • 2023-01-25
  • 1970-01-01
  • 2015-02-27
  • 1970-01-01
  • 1970-01-01
  • 2012-11-02
  • 2021-11-30
  • 2014-12-19
相关资源
最近更新 更多