【问题标题】:Importing and exporting to a text file - Python导入和导出到文本文件 - Python
【发布时间】:2016-12-18 13:47:27
【问题描述】:
我正在尝试创建一个程序,通过向您提问来诊断您的计算机。目前,问题和答案都在程序的列表中。我如何将所有问题和答案保存在 .txt 文件中,并在程序运行时将它们导入。此外,我如何能够将用户输入导出到另一个 .txt 文件。
谢谢
【问题讨论】:
-
你到底坚持哪一部分?这既不是代码编写服务,也不是教程服务;请学习How to Ask并提供具体问题。
标签:
python
python-3.x
diagnostics
【解决方案1】:
如果您将文本文件格式化为每行一个问题或答案,您可以简单地使用文件对象的readlines 方法。
假设这是文件foo.txt:
This is the first line.
And here is the second.
Last is the third line.
要将其读入列表:
In [2]: with open('foo.txt') as data:
...: lines = data.readlines()
...:
In [3]: lines
Out[3]:
['This is the first line.\n',
'And here is the second.\n',
'Last is the third line.\n']
请注意这些行仍然包含换行符,这可能不是您想要的。
要改变这一点,我们可以这样做:
In [5]: with open('foo.txt') as data:
lines = data.read().splitlines()
...:
In [6]: lines
Out[6]:
['This is the first line.',
'And here is the second.',
'Last is the third line.']