Thursday, November 12, 2015

Files - Python

Files - Python

Open a file:
open(): return a handle to operate the file
syntax:
handle = open(filename, mode)
fhandle = open('mbox.txt', 'r')
handle is not the actual data from the file, it is a "connection".


The newline character:
\n
it is one character.

Can treat a file handle as a sequence: (a sequence is an ordered set)
xhandle = open('mbox.txt')
for cheese in xhandle:
    print cheese

Read the Whole file (into a single string inlucding the newlines):
inp = xhandle.read()

Searching through the file:
for and if
line.startwith('xxx')
line.rstrip() #strip the white space(s) at the right of the line

Skipping with continue:
use continue in for and if

'xxx' in line
not 'xxx' in line

Prompt for the file name:
fname = raw_input('Enter the file name: ')

Try to open a file:
fname = raw_input...
try:
    fhand = open(fname)
except:
    print "Cannot open the file: ", fname
    exit()

No comments:

Post a Comment