Write to Disk
my_file = open("sample.txt","w")
my_file.write("Sausage\n")
my_file.write("Egg\n")
my_file.write("Chips\n")
my_file.close()
my_file = open("hello.txt","w")
lines_of_text = ["Sausage\n","Egg\n","Chips\n"]
my_file.writelines(lines_of_text)
my_file.close()
Read from Disk
Read One Line from Disk
my_file = open("sample.txt","r")
print(my_file.readline())
my_file.close()
Read all Lines and Strip Line Breaks
file = open("sample.txt", "r")
for line in file:
print(line.rstrip('\n'))
or
file = open("sample.txt", "r")
for line in file:
print(line, end = "")
Read Lines into a List
my_file = open("sample.txt","r")
print(my_file.readlines())
my_file.close()
Exercise
- In Python, open a file object with write access to a file called “people.txt”.
- Write the following three names to the file: George, Alison, Jasprit.
- Close the file object
- Open the file in Notepad and check the names were written correctly.
- Use Notepad to create a text file called “shopping.txt”. Add the following items, one item per line: milk, sugar, flour, 6 eggs, butter, raisins, raspberry jam
- In Python, open a file object with read access to shopping.txt
- Use a for loop to print out the items in your shopping list
- In Python, open a file object with write access to a file called “todo list.txt”
- Write a question loop that will prompt the user “Add another item”
- If the user enters “N” the loop will terminate and the file object will be closed.
- Otherwise, the item entered will be written to the file object
- Run your program and check that the todo list is created.