90 likes | 100 Views
Python Camp. Session 6: Data Structures and File Handling Lists File Handling Edit: We actually spent this session looking at for loops and the Turtle module – no slideshow but see Mark’s Introduction to Python book or many and various corners of the Internet for more on Turtle.
E N D
Python Camp Session 6: Data Structures and File Handling • Lists • File Handling • Edit: We actually spent this session looking at for loops and the Turtle module – no slideshow but see Mark’s Introduction to Python book or many and various corners of the Internet for more on Turtle.
What’s wrong with this code? player1 = “Dave” player2 = “Angelica” player3 = “Steve” player4 = “Claire”print(player1) print(player2) print(player3) print(player4)
A better version player = [“Dave”, “Angelica”, “Steve”, “Claire”]print(player)This is called a listIt is similar (though subtly different) to an arrayPython doesn’t support arrays, lists are very close and fine for GCSE
Key Rules and Terms • Liste.g. names = [“Graham” , “Eric” , “Terry” , “John” , “Michael”] • Indexe.g. names[1]n.b. Remember to count from 0! • Appende.g. names.append(“Mark”) • ine.g. if “Terry” in names: • positione.g. position = names.index(“Terry”)
File Handling - Reading • Open a file:file = open(“filename” , “mode”)e.g. file = open(“data.csv” , “r”)print(file)input()line = file.readline() # Read just the first lineprint(line)input()data = line.split() # Split the line into a listprint(data)input()
Top Tips • Using readline(), Python keeps track of position • Try:for line in file: print(line) # Or some other processing • Remember to use file.close() to tidy up • Think database – storing data in records is an efficient way to store data
Writing data • file = open(“newTextFile.txt” , “w”) • This will create a blank, empty file (deleting any existing data) • Use file.write() to add data to it • Add your own newline characters (“\n”) – like <br> in HTML • Remember to use file.close()! • file = open(“exisitngTextFile.txt” , “a”) • This will preserve existing data and append to the end of the file • There is no trivial way to edit a file in the middle
Further topics to explore • 2D arrays / lists • Sorting lists • Python specific: • Tuples • Dictionaries