[英]How to print a variable in a txt file with Python 3
我一直在网上搜索,但没有找到任何解决方案。
这是我的文本文件:
我想要 x cookies
他想要你 cookies
我希望 python 脚本从用户输入中导出 x 和 y 中的值。 这是脚本:
xcookies = input("How much cookies do you want?")
ycookies = input("How much cookies does he want?")
我在网上找到了一些脚本,但我永远无法保留原始文本文件中的文本并在此文本文件中导出变量。
有人可以帮我吗?
目前尚不清楚您想在脚本中达到什么。
请让你的问题更具体。
无论如何,您可以以此为指导:
为了读取文本文件并写入文本文件,您可以执行以下操作:
with open("path/to/file.txt", "r") as f:
data = f.read()
使用它,您可以读取文件的内容然后解析它
(使用data.split()
或任何你需要的东西)。
从用户那里获得所需的输入后,
您可以通过执行以下操作将内容写回文件:
with open("path/to/file.txt", "w") as f:
f.write(content)
请参考这些教程:
这会将 append 您的变量添加到 MyFile.txt 的末尾,该文件与 python 脚本位于同一目录中。
# Open the text file
txt_file = open("MyFile.txt","a")
# Append new line
txt_file.write('\n')
# Append your variables
txt_file.write(xcookies + '\n')
txt_file.write(ycookies + '\n')
# Close file
txt_file.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.