Python Forum
Read a file - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Read a file (/thread-8856.html)



Read a file - afovio - Mar-10-2018

Hello, all. I'm having trouble noticing the explanation of the wiki, the link below show my problem.

Input and Output

I created a file in .txt and another in .py Here's the description of the file:

quotes.txt
1. Never in the field of human conflict was so much owed by so many to so few. -Winston Churchill
2. Do you have to have a reason for loving? - Brigitte Bardot
3. Minimalism wasn't a real idea - it ended before it started. - Sol LeWitt
4. The best place to find God is in a garden. You can dig for him there. - George Bernard Shaw
5. There cannot be a crisis next week. My schedule is already full. - Henry Kissinger

teste.py
f = open('quotes.txt')
for line in f.readlines():
	print(line, end='')
I intend that each time I run the file, a different quote is displayed randomly.


RE: Read a file - j.crater - Mar-10-2018

You could, for example, store each line in a list (of quotes), instead of print it.
And to choose a random one, use random module's random.choice.

As an aside, it is recommended to use a context manager when working with files (here is one of many resources on the subject).