[Tutor] Importing data from a file.

Alan Gauld alan.gauld at btinternet.com
Thu Mar 21 17:17:28 CET 2013


On 21/03/13 13:43, Shall, Sydney wrote:
> I have an elementary question provoked by another post today.
>
> 1. Is it the case that ALL imported data from a file is a string?

Assuming you mean data read from a file rather than modules imported 
using 'import' then the answer is 'it depends'.

Most files are text files and the data is stored as strings and 
therefore when you read them back they will be strings. You then convert 
them to the native data using int(), float() etc.

Some files are binary files and then the data read back will be bytes 
and need to be decoded into the original data. This is often done using 
the struct module.

Either way if you use the Python read() operation on a file
you will get back a bunch of bytes. What those bytes represent depends 
on how they were written. How they are interpreted is down to the 
programmer.


> 2. Does this therefor imply that said data has to be processed
> appropriately to generate the data in the form required by the program?

Yes, always.

> 3. Are there defined procedures for doing the required processing?

Yes, for the standard types. For custom types and arbitrary binary data 
you need to find out what the original encoding was and reverse it.

HTH,

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list