Tuesday, April 12, 2011

Working in Files

So files has been a tricky spot for me

i think because im not comfortable with having code grab things off of a screen.

cause how does it know when it "sees" the letter "A" in a file that it is actually A?
And how does it keep track of what line it's in?


according to Mitra's instructions:
if the file is small and can be read in as a single string then you can do this:

infile= open("sample.txt", "r")
filecontent=infile.read()


however if the file is too large to fit in memory then you will have to read the file line by line
that command is readline()

to read remaining lines the command is readlines()

the simplest way to read a line line by lines would be to:

for line in openfile:
#process the line
line=line.rstrip("\n") #strips the newline character at the end
...
infile.close()


ahhhh okay!!!!
file=openfile.read() #reads the whole file in
file=openfile.readline() #reads one line and
file=openfile.readlines() #reads everything in the file and puts it in a list with each element being a line


#what's the advantage of this( readlines() )? it's the same
# as the for line in openfile
#it's different by sticking each line as an element in a list



################
  1. use readlines() when you want a list with each element in the list being the line of the text
  2. use readline() when you want only one line and python remembers the second line is next
  3. use the for loop (for line in openfile (see above)) to work line by line in an iterative fashion
  4. use openfile.read() when you want the entire file as one string

No comments: