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

This is introductory course for computer science. Its about basic concepts involving in computer programming, structure and working. Key points in this lecture handout are: File Input, Programs Often Take Input from a File, a Simple Echo Program, Another Gotcha

Typology: Study notes

2012/2013

Uploaded on 09/28/2013

noob
noob 🇮🇳

4.4

(25)

105 documents

1 / 6

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Lecture Notes CPSC 121 (Fall 2012)
Today
File Input
Reading
Ch 15
Homework
HW 10 due
HW 11 out
S. Bowers 1 of 6
pf3
pf4
pf5

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