Docsity

File Input - Computer Science - Lecture Notes, Study notes of Computer Science

Partial preview of the text

Download File Input - Computer Science - Lecture Notes and more Study notes Computer Science in PDF only on Docsity!

Today

  • File Input

Reading

  • Ch 15

Homework

  • HW 10 due
  • HW 11 out

Reading from a file

Programs often take input from a file

  • Python provides various functions for working with files:
  • The open function opens a file: open(filename)
  • Assumes filename is a text file
  • Opens it for reading (default)
  • Returns a file object (reference)
  • If file not in current directory, need to give full path to the file

A simple echo program

  • Create a “test.txt” file: hello world spam ham eggs
  • Create an “echo.py” script: def main(): the_file = open(’test.txt’) for line in the_file: print(the_line) # prints each line in the_file main()

When this runs ...

  • We end up with extra lines
  • This is because each line in “test.txt” has a newline (’\n’)

Close files when done with them

  • Call the close() method to release resources

the_file = open(’test.txt’) ... do stuff ... the_file.close()

  • Once the file is closed ...
  • Trying to access its contents will give an error

Each line is considered a string

  • What if we wanted to treat the file as a list of numbers?
  • Create a file “nums.txt”

10 20 30 40 50 60

  • Now convert the strings to numbers:

the_file = open("nums.txt") for line in the_file: num = int(line) print(num)

  • Note that in this case, we don’t get the extra lines!
  • The int function removes them for us here