Previous Lecture Lec 11 Next Lecture

Lec 11, Mon 02/10

Lecture 11: File I/O + Binary Numbers

Feedback from this week’s lab:

Announcements

HW07

No Common Final

Review

What is the output of this code?

for x in range(1, 4, 2):
    print (2**x, end = " "

Output: 2 8

Answer explained:

What does end = " " do?

Starting iteration using range()

start = 2
end = 9
step = 3
for i in range(start, end, step):
    print i

String iteration

s = "Hi there!"
for c in s:
    print(c) # prints the characters in s
    
for i in range(len(s)):
    print (i) # prints the indicies of the letters in s

Indexing a string

for i in range(len(s)):
    print(s[i]) # prints each letter in s

File I/O

Opening and reading

fobj = open("info.txt") # Open "info.txt"
content = fobj.readlines() 
fobj.close() # Close "info.txt"

Opening and writing

fobj = open("info.txt", "w") # "w" is a write flag that says we will overwrite any contents in file 
content = fobj.write()
fobj.close()

Demo

fobj = open("sample_file.txt", "w")

for x in range(1, 4, 2):
    fobj.write(str(2**x) + " ")

fobj.close

Output: contents in “sample_file.txt” are changed. Now the file contains: 2 8

fobj = open("sample_file.txt", "a") # "a" is an append flag that says we will add to any contents in file 

for x in range(1, 4, 2):
    fobj.write(str(2**x) + " ")

fobj.close

Output: 2 8 is added to contents in “sample_file.txt”

Can be tedious to open file every time, so we can store the contents in the file in a variable.

fobj = open("sample_file.txt", "r") # "r" is an read flag that reads the contents in file 

contents = fobj.readlines() # Store file object in a list variable 

fobj.close

print(contents)

for line in contents:
    print(line) # Print each line separately instead of as a list

Another example:

file_obj = open("another_sample.txt")

message = file_obj.readlines() # Each line in another_sample.txt is an element in the list, message

for line in message:
    print(line, end = "") # Prints each element in message
    
# Could also print each element in message using indexing explicitly:
for i in range(len(message)):
    print(message[i], end = "")
    
print("Contents of message:", message) # Prints message as a list

Looking forward to next topic:

This is how we count:

In Binary, we only have two digits: 0 and 1

We will be writing a function where given a string, we will confirm if this is a binary string or not (contains only binary characters)

def only_binary(input_str):
    """
    If input_str has only 1s and 0s 
        return True
    Otherwise,
        return False
    """

    for char in input_str:
        if char != '1' or char != '0':
            return False
    return "stub"
only_binary('1')
False
only_binary('0')
False

Hmmm, not what we expected. Debugging skill: any time your function is not acting as expected, use the simplest possible input to see what is happening.

def only_binary(input_str):
    """
    If input_str has only 1s and 0s 
        return True
    Otherwise,
        return False
    """

    for char in input_str:
        if char != '1' and char != '0': # Notice we changed OR to an AND
            return False
    return True
only_binary('1')
True
only_binary('0')
True

Now that our function is working properly, we can give it more complicated inputs.

only_binary('1011')
True
only_binary('10171')
False