8.3 - File Handling Flashcards
What is a file
a collection of data stored by a computer program to be used again
Why is data stored in a file
> stored permanently
> Data stored in a file can thus be accessed by the same program at a later date or accessed by another program
> Data stored in a file can also be sent to be used on other computer(s).
Pseudocode to write to a file
DECLARE TextLine : STRING
DECLARE MyFile : STRING
MyFile ← “MyText.txt”
OPEN MyFile FOR WRITE
OUTPUT “Please enter a line of text”
INPUT TextLine
WRITEFILE, TextLine
CLOSEFILE(MyFile)
Pseudocode to read from a file
OUTPUT “The file contains this line of text:”
OPEN MyFile FOR READ
READFILE, TextLine
OUTPUT TextLine
CLOSEFILE(MyFile)
Python write to a file
MyFile = open (“MyText.txt”,”w”)
TextLine = input(“Please enter a line of text “)
MyFile.write(TextLine)
Myfile.close()
Python read from a file
print(“The file contains this line of text”)
MyFile = open (“MyText.txt”,”r”)
TextLine = MyFile.read()
print(TextLine)
Myfile.close()