0% found this document useful (0 votes)
33 views18 pages

Chapter Three Exceptional Handling and Input and Outputs

The document discusses file input and output in Python, explaining how to open files using open() or file(), read and write data to files using methods like readline(), read(), write(), and writelines() on the file object, and how files can be used for input and output like sys.stdin and sys.stdout. It also notes that files are iterable objects similar to lists and provides examples of reading an entire file into a string or reading lines into a list.

Uploaded by

Student Ritwan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views18 pages

Chapter Three Exceptional Handling and Input and Outputs

The document discusses file input and output in Python, explaining how to open files using open() or file(), read and write data to files using methods like readline(), read(), write(), and writelines() on the file object, and how files can be used for input and output like sys.stdin and sys.stdout. It also notes that files are iterable objects similar to lists and provides examples of reading an entire file into a string or reading lines into a list.

Uploaded by

Student Ritwan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 18

Chapter Three:

Exception
handling and
input and output
files
File input and
output
• Files are manipulated by creating a file object
• f = open("points.txt", "r")

• The file object then has new methods


• print f.readline() # prints line from file

• Files can be accessed to read or write


• f = open("output.txt", "w")
• f.write("Important Output!")

• Files are iterable objects, like lists


open() and file()

• These are identical:


f = open(filename, "r")
f = file(filename, "r")
• The open() version is older
• The file() version is the recommended way to open
a file now
• We will be using both
We
ope
crea n a file
ting f
File I/O
file or inpu Name of the file
obje t
ct f ,

f = file("foo", "r")
We read a line
line = f.readline()
from file object f
print line,

ct
f.close()
ob j e
s file
e th
i # Can use sys.stdin as input;
clo s
We # Can use sys.stdout as output.
Files: Input
input = open(‘data’, ‘r’) Open the file for input

S = input.read() Read whole file into


one String
S = input.read(N) Reads N bytes
(N >= 1)
L = input.readlines() Returns a list of line
strings
Files: Output
output = open(‘data’, ‘w’) Open the file for
writing
output.write(S) Writes the string S to
file
output.writelines(L) Writes each of the
strings in list L to file
output.close() Manual close
Thanks
Prepared by: Eng Mohamed
Ahmed Mohamed

You might also like