Lecture 24 - Writing Files

Lecture Date: Monday, March 21

First, we will finish up with our temperature reading program.

Reading files is great, but what if we want to write stuff to disk? How can we do this… and not blow up our computers? Consider what would happen if we created an infinite loop….

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Mark Sherriff (mss2x)

import os

print(os.listdir(os.getcwd()))

total_size = 0
for filename in os.listdir(os.getcwd()):
      total_size = total_size + os.path.getsize(os.path.join(os.getcwd(),filename))

print(total_size)

output_file = open("output_file.txt", "w")

output_file.write(str(os.listdir(os.getcwd())))
output_file.write('\n')
output_file.write(str(total_size))
output_file.close()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
shopping_list = []

# Read the file into the list
datafile = open("shopping_list.txt", "r")

for line in datafile:
    line = line.strip()
    shopping_list.append(line)
datafile.close()

print("Your current shopping list is:")
for item in shopping_list:
    print(item)

print()
while True:
    item_to_add = input("Items to add (NONE to stop): ")
    if item_to_add.upper() == "NONE":
        break
    shopping_list.append(item_to_add)

print()
while True:
    item_to_remove = input("Items to remove (NONE to stop): ")
    if item_to_remove.upper() == "NONE":
        break
    shopping_list.remove(item_to_remove)

print()
print("Your current shopping list is:")
for item in shopping_list:
    print(item)

print()
print("Saving to shopping_list.txt...")
datafile = open("shopping_list.txt", "w")

for item in shopping_list:
    datafile.write(item + "\n")