Reads a plain text file : Text file « File « Python Tutorial

Home
Python Tutorial
1.Introduction
2.Data Type
3.Statement
4.Operator
5.String
6.Tuple
7.List
8.Dictionary
9.Collections
10.Function
11.Class
12.File
13.Buildin Function
14.Buildin Module
15.Database
16.Regular Expressions
17.Thread
18.Tkinker
19.wxPython
20.XML
21.Network
22.CGI Web
23.Windows
Python Tutorial » File » Text file 
12.3.4.Reads a plain text file
def open_file(file_name, mode):
    try:
        the_file = open(file_name, mode)
    except(IOError), e:
        print "Unable to open the file", file_name, "Ending program.\n", e
        raw_input("\n\nPress the enter key to exit.")
        sys.exit()
    else:
        return the_file

def next_line(the_file):
    line = the_file.readline()
    line = line.replace("/""\n")
    return line

def next_block(the_file):
    category = next_line(the_file)
    
    question = next_line(the_file)
    
    answers = []
    for i in range(4):
        answers.append(next_line(the_file))
        
    correct = next_line(the_file)
    if correct:
        correct = correct[0]
        
    explanation = next_line(the_file

    return category, question, answers, correct, explanation

trivia_file = open_file("trivia.txt""r")
title = next_line(trivia_file)
score = 0

category, question, answers, correct, explanation = next_block(trivia_file)
while category:
    print category
    print question
    for i in range(4):
        print "\t", i + 1"-", answers[i]

    answer = raw_input("What's your answer?: ")

    if answer == correct:
        print "\nRight!",
        score += 1
    else:
        print "\nWrong.",
    print explanation
    print "Score:", score, "\n\n"

    category, question, answers, correct, explanation = next_block(trivia_file)

trivia_file.close()
12.3.Text file
12.3.1.First Python Programs
12.3.2.File Read and Display
12.3.3.Demonstrates reading from a text file
12.3.4.Reads a plain text file
12.3.5.Writing to a text file
12.3.6.Open a file and save text to it
12.3.7.Storing and parsing Python objects in files
12.3.8.print to a file
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.