Learning Python - Week 6

This was my final week of Python! To finish it off I learned about File IO and the OS module which help with creating files and running files.

File IO

You can use python to open files and there are a few ways to do this using File IO. You can use this to read from a file, add to an existing file or overwrite a file. One is just using the open method which would need to be followed up by the close method and the Second being using with which does all of that for you:
First option:

myfile = open('/Users/<user>/Documents/Coding/Python/LearningPython/fileIO-example/sample.txt') # cant have this file be opened more than once

content = myfile.read() # reads the contents of sample.txt from beginning to end
print(content)

myfile.seek(0) # will put the cursor at the beginning of the file. resets the cursor

print("---------------")
data = myfile.read() # will not read if printed. The read function takes the cursor from the beginning all the way to the end. so when the content variable is printed the cursor is at the end and will not go back.
print(data)

myfile.seek(0) # will put the cursor at the beginning of the file. resets the cursor

print("---------------")

content_list = myfile.readlines() # to read each line there is a readlines method. each line in the file will be saved in its own element in the list

myfile.close() # will close the file

Second Option: ( I prefer this way )

with open('/Users/evanpavone/Documents/Coding/Python/LearningPython/fileIO-example/sample.txt', mode='a') as my_file:
    """
    This open syntax already opens and closes the file
    If I change the filename it will make a new file in that location if I use the write mode
    MODES:
    a = append - adds to the file
    w = write - overwrites the file. The data will be replaced
    r = read - cannot write to it. Read only mode
    r+ = read and write
    w+ = override the file completely and have the ability to read it
    """
    my_file.write("\nThis is my sentence") # appended to the end of the file
File IO Exception Handling

Last week I talked about exception handling using try and except. Well, this week I found out that you can specify what to do for each type of error. For example, if I had a TypeError, I could specify what would happen if a type error occurred if I ran my code.

my_file = None

try:
    my_file = open('/Users/evanpavone/Documents/Coding/Python/LearningPython/fileIO-example/sample.txt', mode="r")
    print(my_file.read())
except IOError:
    """
    There are different types of exception errors. TypeError, FileNotFoundError etc...
    You can capture specific errors
    """
    print("Issue with working with the file...")
except:
    # general catch all error
    print("Error occurred, logging to the system")
finally:
    if my_file != None:
        my_file.close()
    print("This will always run regardless of whether we have an exception or not")

print("This line was run...")
OS Module

From what I learned about OS Module is that it helps with file paths and making sure that the folder contains files, etc.Os Module all starts with importing os at the top of the file import os. Importing OS allows you to use a bunch of methods like getcwd, mkdir, makedirs, rmdir, etc. Here are a bunch of methods within the os module:

os.cwd() # gets the current working directory
os.chdir(“/Users/<user>/Desktop”) # changes directory location - in this case changes directory to desktop
os.listdir() # lists the contents of the directory
os.mkdir() # creates a folder in the current directory
os.makedirs() # creates multiple directories - good for having nested folders
os.rmdir() # deletes specific directory
os.remove() # removes files from the directory
os.walk() # “walks you through a directory and tells you each file and folder - I will show example with a for loop
os.environ.get("HOME") + "/" + "myfile.txt" # ->  /Users/<user>/myfile.txt
os.path.join(os.environ.get("HOME"), "myfile.txt" # -> /Users/<user>/myfile.txt
os.path.basename("/bin/tools/myfile.txt") # myfile.txt - used to get basename... thats the file at the directory location given
os.path.dirname("/bin/tools/myfile.txt") #  /bin/tools - get the directory name only, not the file
os.path.split("/bin/tools/myfile.txt") # ('/bin/tools', 'myfile.txt') - will give directory name and basename in a tuple
os.path.exists("/bin/tools/myfile.txt") # False - used to check if the path exists on the computer
os.path.isfile("/bin/tools/myfile.txt") # used to check if file exists in the specified path
os.path.isdir("/bin/tools/myfile.txt") # check if directory exists in the specified path
os.path.splitext("/bin/tools/myfile.txt") # ('/bin/tools/myfile', '.txt') - get file with path and file extension in a tuple

Example of using the walk method in a for loop:

import os

for dirpath, dirnames, filenames in os.walk("/Users/<user>/Documents/Coding/Python/LearningPython/myfolder"):
    # unpacking
    print(dirpath)
    print(dirnames)
    print(filenames)
    print(" ------------ ")

"""
/Users/<user>/Documents/Coding/Python/LearningPython/myfolder - dirpath
['stuff'] - dirnames
['sample.txt'] - filenames
 ------------ 
/Users/<user>/Documents/Coding/Python/LearningPython/myfolder/stuff - dirpath
['data'] - dirnames
['sample.txt'] - filenames
 ------------ 
/Users/<user>/Documents/Coding/Python/LearningPython/myfolder/stuff/data - dirpath
[] - dirnames - means no directory
['peacock.jpeg'] - filenames
 ------------ 
"""
What I am thinking

I am already starting to think of possibilities using these. I am curious to see if I could make a script that would install a selected language to a pc. Like, if I wanted to install Rails to a pc I could run a file that would ask me what language I want to install and I would select Rails and it would go through the process of installing it. I’m just rambling right now but I’m very curious.

What now

Since this was my last week of learning python I am going to be get a better understanding of it and hopefully take the certification exam in the next few weeks. I had a lot of fun with python and I think it is up there with my favorite languages.

15