Importing and exporting to a text file - Python

398 views Asked by At

I am trying to create a progam which diagnoses your computer by asking you questions. At the moment, the questions and answers are in lists in the program. How would I have all the questions and answers in a .txt file and import them in when the program runs. Also, how would I be able to export the users inputs to another .txt file. Thanks

1

There are 1 answers

0
Roland Smith On

If you format your text files as one question or answer per line, you can simple use the readlines method of file objects.

Let's say this is the file foo.txt:

This is the first line.
And here is the second.
Last is the third line.

To read this into a list:

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']

Note how these lines still contain the newline, which is probably not what you want. To change that we could do it like this:

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.']