Download presentation
Presentation is loading. Please wait.
1
File Handling
2
File Handling One of the issues with using variables to store data is that as soon as the program is closed the contents (e.g. a password) are deleted and reset once the program is re-opened. That would not be suitable in the real world so we must write data to files that could then be recalled at a later date.
3
File Handling – writing to file ‘wt’
#Write the following code and save to your area. print(“Below is the code to write data to a text file\n”) #writing to file myFile = open('details.txt', 'wt') myFile.write ('I have written this data to file\n') myFile.write ('I have written this data to file again\n') myFile.write ('I have written this data to file yet again!\n') myFile.close()
4
File Handling – writing to file ‘wt’
#Run the code and then close the program, there should now be a details.txt file stored in the same directory as your python code. Re-open and add the code below: print("Congratulations you have written three lines of text to file!") print("This is stored as a text file in the same folder as this program") print("Now to read from the text file so that the details can be displayed in this code")
5
File Handling – reading from file ‘rt’
#enter the code below: #reads contents, stores in a variable then prints myFile = open('details.txt', 'rt') contents = myFile.read() #stores all details from text file in contents variable print(contents) myFile.close()
6
File Handling – reading from file ‘rt’
#enter the code below: print("\n That's great but it reads all of the contents together and then outputs to screen") print("What if we want to read a line at a time?")
7
File Handling – reading from file ‘rt’
#enter the code below: #reading contents a line at a time myFile = open('details.txt', 'rt') for line in myFile: #for loop to read a line at a time print(line) print("\nAnd the next line has...") myFile.close()
8
File Handling – Applying skills
Write a program that reads a list of numbers from a file then outputs the average. So if your file contained: Your program would output: 38 Hints: myFile.write ('3\n'), etc. total = total + int(line) #to add the numbers #more code required
9
File Handling – appending to file ‘a’
#enter the code below: myFile = open("details.txt", "a") myFile.write("appended text") myFile.close() #reads contents, stores in a variable then prints myFile = open('details.txt', 'rt') contents = myFile.read() print(contents)
10
File Handling – developments to your code
#Create a Menu using print (and an input) for the following: ****File Handling**** 1…..Write to file 2…..Read data from file 3…..Append data to file Please enter selection: _ #Use procedures for each option and an if elif to call the correct procedure depending on the user’s selection.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.