| Line 310: |
Line 310: |
| | | | |
| | == Files == | | == Files == |
| | + | '''Counting lines in a file''' |
| | + | <source lang="python"> |
| | + | fhand = open("words.txt") |
| | + | count = 0 |
| | + | for line in fhand: |
| | + | count = count + 1 |
| | + | print "line count", count |
| | + | </source> |
| | + | '''Reading the whole file''' |
| | + | <source lang="python"> |
| | + | fhand = open("words.txt") |
| | + | inp = fhand.read() # reads the whole file into memory |
| | + | print len(inp)# returns the number of characters in a file |
| | + | print inp # prints the whole file |
| | + | </source> |
| | + | '''Searching through a file''' |
| | + | <source lang="python"> |
| | + | fhand= open("mbox-short.txt") |
| | + | for line in fhand: |
| | + | # line = line.rstrip() |
| | + | if line.startswith("From:"): |
| | + | line = line.rstrip() # better here |
| | + | print line |
| | + | </source> |
| | + | '''File names and paths''' |
| | + | <source lang="python"> |
| | + | fname = raw_input("Enter a file name: ") |
| | + | if fname[0:2] == "~/": #Check to see if it starts with a ~ and a slash |
| | + | #If it doesn't start with the ~/, then |
| | + | #the user could be referring to a valid file |
| | + | #like "~.py" (I checked: it is possible.) |
| | + | #notice below replace is valid on Mac OSX only (and not a good approach overall, cause not portable at all) |
| | + | fname = fname.replace('~',"/Users/"+raw_input("Enter your short user name: "),1) |
| | + | workingfname = fname.replace("\\",'') #This for proper escaping of a valid folder named '~' as '\~', you can also use './~' as Python automatically escapes for you. |
| | + | #go back to normal program now |
| | + | handle = open(workingfname,'r') # . . . |
| | + | for line in handle: |
| | + | print line |
| | + | print "\n"+("That was "+fname+".").center(40) |
| | + | </source> |
| | + | |
| | == Class == | | == Class == |
| | == MySQLdb == | | == MySQLdb == |
| | == os.system() == | | == os.system() == |