Python Forum

Full Version: Read a file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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.
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).