Python 2.7 Tutorial Pt 10

Python PictureIn this Python 2.7 Tutorial I focus on how to work with files in Python 2.7. Specifically I show you how to:

  • Open a file and access its contents
  • Break file content up into pieces and analyze it
  • Sort file information
  • Write information back to a file
  • Search for files in a directory
  • Create and Delete directories

Like always, a lot of code follows the video. If you have any questions or comments leave them below. And, if you missed my other Python Tutorials they are available here:

Here is All the Code from the Video

It is heavily commented, but leave questions below if anything is confusing.

#! /usr/bin/python

import os

def retrieveFile():
# Will catch any errors triggered if the file doesn’t exist
try:
bestStudent = {}
bestStudentStr = “The Best Students Ranked\n\n”

# Will open the file studentgrades.txt and store it in the file f
f = open(‘studentgrades.txt’)

# If the file isn’t found a friendly error will print to screen
except(IOError), e:
print “File not found”, e
else:

# Splits each line in the file into 2 strings
# Creates a dictionary using those 2 strings as key value pairs
for line in f:
name, grade = line.split()
bestStudent[grade] = name

# Closes the file
f.close()

# Sorts the grades from highest to lowest and stores them in a new string
for i in sorted(bestStudent.keys(), reverse = True):
print(bestStudent[i] + ‘ scored a ‘ + i)
bestStudentStr += bestStudent[i] + ‘ scored a ‘ + i + “\n”

print(“\n”)

print bestStudentStr

# Outputs the string to a new file ‘w’ stands for write to file
outToFile = open(‘studentrank.txt’, ‘w’)
outToFile.write(bestStudentStr)

# Closes the created file
outToFile.close()

print(‘Finished Update’)

return

def directoryPlay():

# Outputs the files stored in directory /usr
print os.listdir(“/usr”)

# Checks if /usr/bin/python is a directory and then a file
print os.path.isdir(“/usr/bin/python”)
print os.path.isfile(“/usr/bin/python”)

# Outputs all files in directory /usr
dirList = os.listdir(“/usr”)

# Cycles through files in /usr and outputs files if one of them is a directory
for file in dirList:
if os.path.isdir(“/usr/”+file):
print os.listdir(“/usr/”+file)
else:
continue

# How to create a new directory and then how to delete it
os.mkdir(“/Users/derekbanas/Documents/Testing”)
os.rmdir(“/Users/derekbanas/Documents/Testing”) # Works if program has permission

return

def main():
retrieveFile()
directoryPlay()

if __name__ == ‘__main__’: main()

6 Responses to “Python 2.7 Tutorial Pt 10”

  1. RXR says:

    Hi,

    Thank you for your effort and time. Please keep the Python videos going. Great work. 🙂

    Just a bit of correction on this video if I may? It seems like this code lost one of your record!
    Your code: “bestStudent[grade] = name” can not handle more then one record that happen to
    have the same score or grade.

    I love your video and your skills to create this lessons. I know it is not easy to do. More power to you. Thank you
    RXR

  2. navdeep says:

    Hi Derek
    Many Many Thanks to you for putting up python tutorials.
    They are very very helpful and your way of teaching is excellent.
    Please upload more.

    Regards

    • admin says:

      Thank you very much 🙂 I really do need to extend these tutorials and I plan on covering DJango, mod_python, scgi, FastCGI, mod_wsgi and more. Thank you for the request

  3. Matze says:

    Hello Derek, Eclipse shows me the following Error after I typed in the Code until 4:10 in the Video. Could you tell me what went wrong? Thanks for your great Tutorials!

    Traceback (most recent call last):
    File “C:\Users\XXX\workspace\test\test.py”, line 38, in
    if __name__ == ‘__main__’: main()
    File “C:\Users\XXX\workspace\test\test.py”, line 36, in main
    retrieveFile()
    File “C:\Users\XXX\workspace\test\test.py”, line 16, in retrieveFile
    name, grade = line.split()
    ValueError: need more than 0 values to unpack

  4. Anoop says:

    Dear Derek

    Loving ur videos…
    I am also getting the same error as MATZE above, please helpppppp
    Traceback (most recent call last):

    File “/home/anoop/Desktop/Python/Workspace/first/fileio9.py”, line 25, in
    if __name__ == ‘__main__’:main()
    File “/home/anoop/Desktop/Python/Workspace/first/fileio9.py”, line 23, in main
    retrieveFile()
    File “/home/anoop/Desktop/Python/Workspace/first/fileio9.py”, line 12, in retrieveFile
    name,grade =line.split()
    ValueError: need more than 0 values to unpack

    Regards from India
    aNoOp

Leave a Reply

Your email address will not be published.

Google+