CSC111 Playing with Text Files

From dftwiki3
Revision as of 17:41, 14 November 2011 by Thiebaut (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

--D. Thiebaut 08:02, 8 November 2011 (EST)


# filedemo.py
# D. Thiebaut
#

def example1():
    """read the contents of data.txt and displays it on the
    screen"""
    print( "\n\nExample 1" )
    file = open( "data.txt", "r" )
    for line in file:
        print( line, end="" )
    file.close()

def example2():
    """same as example1, but asks user for file name"""
    print( "\n\nExample 2" )
    fileName = input( "file name? " )
    file = open( fileName, "r" )
    for line in file:
        print( line, end="" )
    file.close()

def example3( fileName ):
    """reads a file and returns its contents as a list of strings
    where each string is a line in the original file"""
    print( "\n\nExample 3" )
    file = open( fileName, "r" )
    lines = file.readlines()
    file.close()
    return lines

def example4( fileName, text ):
    """write information to a file"""
    file = open( fileName, "w" )
    file.write( text )
    file.close()
    
def main():
    example1()
    example2()
    lines = example3( "data.txt" )
    print( "".join( lines ) )

    print( "\n\nexample 4" )
    string = input( "Enter a string: " )
    name   = input( "Store in which file? " )
    example4( name, string )

    lines = ["this is line 1", "this is the second line", "and now the third line" ]
    example4( "myDataFile.txt", "\n".join( lines ) )


    
    
    
main()