Skip to main content
Chemistry LibreTexts

2.9: Files

  • Page ID
    206267
  • hypothes.is tag: s20iostpy09ualr
    Download Assignment: S20py09

    Learning Objectives

    Students will be able to:

    Content:

    • Explain how to open a text file for reading and for writing
    • Explain the difference between the read() and readline() functions
    • Explain the purpose of the str() function.
    • Explain the effect of the arguments of the range function when reading data from a file.
    • Explain the purpose of the rstrip(), open(), close(), and write() functions
    • Explain the difference between writing and appending to a file

    Process:

    • Write code that opens, writes to and closes a file
    • Write code that opens, reads from and closes a file

    Prior Knowledge

    • Python concepts from previous activities

    Further Reading

    Information:
    In Python, you can access data from a text file as well as from the keyboard. You can create a text file in any text editing tool. You should only have one data item per line in the file.

    Task 1: Reading a File

    Download the text file named inventory.txt and check its contents against the chemicals listed below, or pasting the list of chemicals into a new text file (named inventory.txt). Create a new program file by entering Python program below. Be sure the saved program is in the same folder as the text file. Run the program

    Python Program 1 inventory.txt file contains:
    def main():
        list = open('inventory.txt')
        chemicals = list.read()
        print(chemicals)
    
    #####call to main#####
    main()
    

     

    methane
    ethane
    propane
    butane
    pentane
    methanol
    ethanol
    1-propanol
    1-butanol
    1-pentanol
    formaldehyde
    acetaldehyde
    propanal
    butanal
    pentanal
    lysergic acid diethylamide
    2-[4-(2-methylpropyl)phenyl]propanoic acid
    N-(4-hydroxyphenyl)acetamide
    methyl 2-phenyl-2-piperidin-2-ylacetate
    2,4,6-trinitrotoluene

     Critical Thinking Questions:

    1. What does the program do?
    2. Explain the purpose and syntax of the first line of code in the user defined function main(). What does the ‘string argument’ for the function open represent?
    list = open('inventory.txt')
    1. Replace the function read()  with the function readline(). Execute the program again. Explain the difference between the two functions: read()  and readline().
    2. Explain the difference between the two functions: read()  and readline().

     

    2. Enter and execute the following code.

    Python Program 2
    def main():
        list = open('inventory.txt')
        for index in range(1,21):
            chemical = list.readline()
            print(str(index) + ". ", chemical)
    
    #####call to main#####
    main()

     

    1.  How does the output from this program differ from the output of the program that used the read() function? What caused the difference?
    2.  What is the subtle difference in the output if the following print statement replaced the one above? Which is better?
    print(index,". ",chemical)
    1.   What does str(index) do in the program above?  Why is the str () function necessary?
    2.   What happens when you change the arguments in the range() function to (1,10)?
    3.   What happens when you change the arguments in the range() function to (0, 30)?
    4.   What do the results from “d.” and “e.” tell you about the arguments of the range() function when you are reading data from a file with a for loop?

     

    Note

    The purpose of the rstrip() function is rather subtle. rstrip() returns a copy of the string after all characters have been stripped from the end of the string (default whitespace characters,  EOL characters, and newline characters).

    3.  The following program is slightly different from Python Program 2. Enter and execute the program.

    Python Program 3
    def main():
        list = open('inventory.txt')
        for index in range(1,21):
            chemical = list.readline()
            print(str(index) + ". ", chemical.rstrip('\n'))
    
    #####call to main#####
    main()

     

    1.   Compare the output from this program to the output in the previous program. What is the   difference?  
    2.   What code caused the difference in the output?
    3.   In this example the rstrip(\n) function strips the newline character (\n) from the string that is read from the file. Why did the newline character get attached to the end of the string in the first place?
    4.   Change the line of code in the print statement to not have the \n as shown below.
    list = open('inventory.txt')

          Is it absolutely necessary to have the newline character be an explicit argument in this function?

    1.   lstrip() is a similar function.  What do you think it does? To test this try replacing rstrip() in your code with lstrip('p'and look at lines 3, 5, 13, and 15.

     

    4.  The following program is slightly different from Python Program 3. Enter and execute the program.

    Python Program 4
    def main():
        list = open('inventory.txt')
        for index in range(1,21):
            chemical = list.readline()
            if len(chemical) >= 10 :
                print(str(index) + ". ", chemical.rstrip())
    
    #####call to main#####
    main()

     

    1.   What does the program display?
    2.   How many features are used in this program?
    3.   Two functions use what is known as dot(.) notation. What are the two functions?
    4.   Examine the output and explain what the len()  function does.

     

    5.  Enter and execute the following program.

    Python Program 5
    def main():
        lastName = input("Enter last name: ")
        firstName = input("Enter first name: ")
        studentID = input("Enter ID: ")
    
        inFile = open("studentInfo.txt", 'w')
        inFile.write("Name: " + firstName + " " + lastName)
        inFile.write("\nStudent ID: " + studentID)
        inFile.write("\n")
        inFile.close()
        print("Done! Data is saved in file: studentInfo.txt")
    
    #####call to main#####
    main()
    
    1.   What output appears on the screen?
    2.   What does the program do?
    3.   Locate the file studentInfo.txt on your computer. The file is stored in the same folder as the program. What is stored in the file?
    4.   What is the purpose of “w” in the following line of code?
    inFile = open("studentInfo.txt", 'w')
    1.   Did you have to create the file: studentInfo.txt before you included it in the program?
    2.   Execute the program again using different input.  Open the studentInfo.txt file.  What is in the file?  Is the data from the first program execution still there?
    3.   Change the ‘w’ to ‘a’ in the open() function. Execute the program again with different input.  Examine the student Info.txt file. What did ‘a’ as an argument in the open() function do? What word do you think ‘a’ represents
    4.   Notice the new function – write(). How many arguments does the write function have?
    5.   How does the write() function know what file to write to?
    6.   What line of code closes the file? Where is it located with respect to other lines of code that interact with the file? Why do you think it is located there?
    7.   Revise the program so that the user can enter three names during one execution of the program. You may need to change the order of some of the code.  Be sure to only include the code that need to be repeated.

    Application Questions:

     

    1. Create a text file that contains 10 numbers between 50 and 100. Write a program that reads the numbers from the file and totals the numbers.  The program should print all the numbers and display the total when all the numbers have been added together.  (Warning! The input from the file will be considered a string.  Be sure to convert the input to int or float – just as you do when numbers are entered from the keyboard.
    2. Revise Python Program 3. Allow the user to enter the name of the file and use the input to open the file.
    Python Program 3
    def main():
        list = open('inventory.txt')
        for index in range(1,21):
            chemical = list.readline()
            print(str(index) + ". ", chemical.rstrip('\n'))
    
    #####call to main#####
    main()