CreateTextFile.py

From dftwiki3
Jump to: navigation, search

D. Thiebaut (talk) 08:41, 25 February 2018 (EST)


# createTextFile.py
# D. Thiebaut
# This program can be run to create a simple text file
# in the directory where this program resides.
# The program first prompts the user for a file name
# which should end with a ".txt" extension (otherwise it
# is automatically added to the end of it.
# The user is then prompted to enter text lines.  The
# program stops when the first empty line is entered.
#
# Copy/paste this code in Idle, and save the code
# as a program you can call "createTextFile.py."
# Save the program in the directory where you want to create your
# text file.

def main():
    # get file name from the user
    fileName = input( "Print enter file name: " )
    if fileName.find( ".txt" ) == -1:
        fileName = fileName + ".txt"
        
    # get text from the user
    print( "please enter the lines of text you want to store in your file." )
    print( "Enter a blank line (type Return twice) to end your input." )
    print( )

    lines = []
    while True:
        line = input( "> " )
        if len( line.strip() ) == 0:
            break
        lines.append( line.strip() )

    # store lines to the text file
    file = open( fileName, "w" )
    for line in lines:
        file.write( line + "\n" )
    file.close()

    # tell user her file is ready
    print( "your file {0:1} is ready to use!".format( fileName ) )

main()