导入和导出到文本文件-Python
我正在尝试创建一个程序,通过向您提问来诊断您的计算机。目前,问题和答案都列在程序的列表中。如何将所有问题和答案保存在.txt文件中,并在程序运行时将其导入。另外,我如何才能将用户输入导出到另一个.txt文件中。导入和导出到文本文件-Python,python,python-3.x,diagnostics,Python,Python 3.x,Diagnostics,我正在尝试创建一个程序,通过向您提问来诊断您的计算机。目前,问题和答案都列在程序的列表中。如何将所有问题和答案保存在.txt文件中,并在程序运行时将其导入。另外,我如何才能将用户输入导出到另一个.txt文件中。 谢谢如果您将文本文件的格式设置为每行一个问题或答案,您可以简单地使用文件对象的readlines方法 假设这是文件foo.txt: This is the first line. And here is the second. Last is the third line. 要将其读入
谢谢如果您将文本文件的格式设置为每行一个问题或答案,您可以简单地使用文件对象的
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.']
确切地说,这其中的哪一部分是你坚持的?这既不是代码编写服务,也不是教程服务;请学习并提供具体问题。