Skip to main content
Engineering LibreTexts

13.3: Introduction - Files

  • Page ID
    26339
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    Often, it is not practical to hold data within a program or expect the user to re-enter the data each time the program is used. Imagine how impractical a word processor would be if documents could not be saved external to the program itself. This is where the concept of files comes in. Ultimately, there are only a handful of things programmer’s normally need to do with files: Open them (i.e., gain access to them, often exclusively, through the use of an appropriate filename and/or path), read data from them, write data to them, move around in them (for example, to skip unneeded sections), and release or close them (so that other programs can gain access). While any program that deals with files will have to open and close them, whether or not they are read, written to and moved within will depend on what the program needs from the file. In the exercise that follows, only opening, reading, and closing will be used. Also, files can be generally of two types, binary and text. Binary files are potentially more powerful but text files are usually easier to use. In the exercise that follows we shall only look at text files. These files contain strings that may be read with any text editor while binary files are generally not readable with ordinary text editors.

    In order to gain access to a file, it must first be opened:

    fil = open( filename, mode )
    

    filename is the literal disk file name such as H:\myfolder\myfile.dat. This is a string that can be hardcoded as a constant (rarely) or more commonly obtained from the user via a input() statement. mode is a string that describes how the file is to be accessed. “r” is used for reading and “w” may be used for writing. There are other modes as well. fil is a file object that is returned to you. It will be needed for subsequent read and write calls. Note that Python allows several files to be open at once, hence the need for file objects. So, a read mode access might look like this:

    fn = input(“Please enter the file name: ”)
    fil = open( fn, “r” )
    

    Once the file object is obtained, data may be read from the file. Data can be read character by character or line by line. Line oriented files are easily read as follows:

    str = fil.readline()
    

    readline() is a file object method. It returns a string that corresponds to the next line of text in the file. Subsequent calls will read subsequent lines. For example, assume you open a basic text editor (such as Notepad) and create a text file that contains the following lines:

    Information is not knowledge
    Knowledge is not wisdom
    Wisdom is not truth
    3.14159
    

    You then save this file as “H:\myfile”. Consider the following snippet of code:

    fil = open(“H:\myfile”, “r” )
    str1 = fil.readline()
    str2 = fil.readline()
    str3 = fil.readline()
    str4 = fil.readline()
    print( str4 )
    print( str3 )
    print( str2 )
    print( str1 )
    

    The result would look like:

    3.14159
    Wisdom is not truth
    Knowledge is not wisdom
    Information is not knowledge
    

    Note that str4 is a string. If you want to turn this into a number so that you can perform math on it, convert it with the float() function:

    mypi = float(str4)
    

    or, if you don’t need the string and just want the floating point value, do it in one line:

    mypi = float( fil.readline() )
    

    When you are done with the file, you need to close it. close() is another file object method:

    fil.close()
    

    Finally, files need to have some manner of internal organization. These can range from very sophisticated “chunk oriented” file structures to simple fixed layouts. Fixed layouts, where every line has a predetermined definition, are easy to access and use when the data are fairly well fixed with few, if any, options or variations. This is the form the assignment shall use.

    Please note, in the interest of brevity, file checking code is not included in the code snippets above. It is possible, for example, for a file to fail to open or for a read operation to result in an error. Any commercially viable program should have these checks but we shall ignore them for now.


    This page titled 13.3: Introduction - Files is shared under a not declared license and was authored, remixed, and/or curated by James M. Fiore.

    • Was this article helpful?