[Tutor] Seeking help with reading and writing files in Python
Alan Gauld
alan.gauld at btinternet.com
Sun Jul 8 19:08:05 CEST 2012
On 26/06/12 19:28, Aristotle wrote:
> The sequence of events that I am using now is to open a program that
> will gather gallons used from user, call a module to make calculations,
> use the info from the module to write info to a file named
> FinalProjectBill.txt.
> ...
> From Instructor:
> You should read from one file (FinalProjectBill.txt) and then write to
> one (BranleyFinal.txt) with the results as we are learning file i/o
> (input/output) -
> ...
> You should not write to your input file.
> My question is why do I need two text files FinalProjectBill.txt and
> BranleyJamesFinal.txt ?
I didn't read this properly the first time around.
The answer to your question is that you don't. It is a design decision.
But, if you write back to the input file it makes things more complex
because you may have to read/write from the same file at the same
time(*). This means moving the file cursor back and forth between the
point where you are reading and the end of the file. There are functions
to do this but it adds a lot of extra overhead and is easy to get wrong.
It is much simpler to read the data from one file and write the output
to another and let Python take care of moving the cursor automatically.
(*)Of course you may choose to read all the input data in, close the
file then overwrite it with your output. That's easy but sometimes the
input file is too big or the processing time too limited to do that. Or
you may need to preserve the data for use in subsequent processing.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list