Python Reading and writing to files

Python Reading and Writing to files.

 

The code below is used to help run a school tuck shop. It will ask you to enter how many products you wish to add. It will then allow you to enter products and prices. When all the data is entered the program will then compile a list in a csv file called 'stocktable.csv'. Check that this file has been created in the same folder where you saved your code. If you run the program again the new data you add will be appended onto the bottom of your csv file.

#program to create csv document and log 2 values and append to csv file
print("Stock list for school tuck shop")
items=int(input("Enter the number of items to add: "))
entries=0
while items>entries:
    product = input("Enter product name:")
    price = input("Enter product price:")
    with open('stocktable.csv', mode='a') as file_:
        file_.write("{},{}".format(product, price))
        file_.write("\n")
        entries=entries+1
print("Finished check your csv file called stocktable to check the data is there.")

Tasks:

  • Run the code and use #comments to explain what it is doing.
  • See if you can create a program that will allow you to enter bands and songs and save them to a new csv file.
  • See if you can amend your code to allow you to enter 3 pieces of data (band, song, release date).
  • See if you can save the data to a text file rather than a csv file.

 

To read the csv file called stocktable that you have created previously run the following code.....

#print the values on the screen from the csv file
import csv
file=open( "stocktable.csv", "r")
reader = csv.reader(file)
list1=[]
list2=[]
for line in reader:
    t=line[0]+","+line[1]
    list1.append(line[0])
    list2.append(line[1])
    print (t)
#numbers from for loop appended to a list for easy access
print("Items displayed as a list.")
print("List 1:",list1)
print("List 2:",list2)

 

Task:

  • Run the code and use #comments to explain what it is doing.
  • Can you edit the code so you can use it to run your data on bands and songs?
  • Can you edit the code so it prints band, song and release date (3 columns of data)?
  • Can you combine the codes so that you can both add and then print the data you have added?
  • Can you build in an if statement so that if someone is an administrator thay can update or read the data, where as if the user is not an administrator they only have read only privileges?