Bruce W
Bruce W

Reputation: 35

Python File Handling

I need to write a program that will write and read to/from a file. I have code that works depending on the order I call functions.

def FileSetup():
    TextWrite = open('Leaderboard.txt','w')
    TextWrite.write('''|    Driver    |      Car       |     Team     |     Grid     | Fastest Lap |  Race Time  |   Points   |
''')
    TextWrite.close()
    TextRead = open('Leaderboard.txt','r')
    return TextRead

def SortLeaderboard(LeaderBoard):
    TextFile = open('Leaderboard.txt', 'w')
    for items in LeaderBoard:
        TextFile.write('\n|  '+items['Driver']+'  |  '+str(items['Car'])+'  |  '+items['Team']+'  |  '+str(items['Grid'])+'  |  '+items['Fastest Lap']+'  |  '+items['Race Time']+'  |  '+str(items['Points'])+'  |')





Leaderboard = Setup()
FileSetup()
TextRead = FileSetup()
TextFile = open('Leaderboard.txt','w')
SortLeaderboard(Leaderboard)
#TextRead = FileSetup()
str = TextRead.read()
print str

Depending on which TextRead = FileSetup() I comment out either SortLeaderboard or FileSetup will work. If I comment out the TextRead after I call SortLeaderboard then SortLeaderboard will write to the file and FileSetup won't. If I call it after then FileSetup will write to the file and Sortleaderboard won't. The problem is only one function writes to the file. I am not able to get both to write to it.

I'm sorry this is really confusing this was the best way I could think of explaining it. If you need me to explain something in a different way just ask and I will try,

Upvotes: 0

Views: 134

Answers (1)

Sebastian Wozny
Sebastian Wozny

Reputation: 17506

Avoid calling .open and .close directly and use context managers instead. They will handle closing the file object after you are done.

from contextlib import contextmanager
@contextmanager
def setup_file():
    with open('Leaderboard.txt','w') as writefile:
        myfile.write('''|    Driver    |      Car       |     Team     |     Grid     | Fastest Lap |  Race Time  |   Points   |
''')
    with open('Leaderboard.txt','r') as myread:
        yield myread


def SortLeaderboard(LeaderBoard):
    with open('Leaderboard.txt', 'w') as myfile:
        for items in LeaderBoard:
            TextFile.write('\n|  '+items['Driver']+'  |  '+str(items['Car'])+'  |  '+items['Team']+'  |  '+str(items['Grid'])+'  |  '+items['Fastest Lap']+'  |  '+items['Race Time']+'  |  '+str(items['Points'])+'  |')


Leaderboard = Setup()
with setup_file() as TextRead:
    SortLeaderboard(Leaderboard)
    str = TextRead.read()
print str

Here you instantiate your own context manager setup_file that encapsulates preparing the file for use, and cleaning up afterwards.

A context manager is a python generator with a yield statement. The control of flow is passed from the generator to the body of the generator after the yield statement.

After the body of the generator has been executed, flow of control is passed back into the generator and cleanup work can be done.

open can function as a context manager by default, and takes care of closing the file object.

Upvotes: 1

Related Questions