T7 - Records and files Flashcards
data structure
- is a collection of elementary data types such as integer, real, Boolean, char or string
record -
is a data structure consisting of a number of fields which can all be of different types
field
- is a single item of data in a record
A file -
is able to store a collection of records
only data type is “string”
CSV (comma-separated values) file:
Each record is on a new line
Each field is separated by a comma
with any text editor
you can create, read and print a CSV file
Create a new file: code
names = newFile(“names.txt”)
Write mode –
allows writing to a file
Append mode –
allows more data to be added to a file
Read mode
– only allows the file to be read
Reading:
from a text file involves
opening the file, processing each line
then closing the file
Here is an algorithm which writes to a text file:
marksFile = open(“marks.txt”)
name = input(“Input student name: “)
mark = input(“Input student mark: “)
marksFile.writeLine(name + “,” + mark + “\n”)
marksFile.close()
“\n”
is the newline character indicating then end of this record
After opening, must close a file why?
- frees up any memory used by having it open
- Once closed, the file cannot be read from or written to without opening it again
To close a file, use: code
myFile.close()