File handling operations Flashcards
writing to a text file
1) before it is accessed/opened, it has to be given a file handle (a reference assigned to the file so the program can use it):
myFile = openWrite(“Sample.txt”)
2) when a file is opened in write mode, a new file is created with the name if it doesn’t already exist
3) if a file already exists, it is overwritten and the existing data is lost most languages have an ‘OpenAppend’ command to prevent this
4) once a file has been read from/written to, it must be closed:
myFile.close()
writing directly
a user can open a file and write data directly to it from the keyboard
myFile = openWrite(“Sample.txt”)
myFile.writeLine(“example”)
myFile.close()
writing indirectly
a program can be coded to save data stored in variables to a text file
e.g.
scoreFile.writeLine(array[index])
reading data from a file
a program can open a text file to read data
data stored in text files can be loaded into the variables of a program
if the number to read to is not known, the endOfFile() function can be used
e.g.
myFile = openRead(“Sample.txt”)
scoreFile = openRead("highScores.txt") for index = 0 to 4 highScores[index] = scoreFile.readLine() next index scoreFile.close()
while NOT scoreFile.endOfFile()
A student has coded a program that allows users to answer a multiple choice test. The user’s name is stored in the ‘userName’ variable and their score in the ‘testScore’ variable.
Insert the code that would allow the score to be saved in a text file with the users name in the filename. [4]
userFile = openWrite(username + “.txt”)
userFile.writeLine(testScore)
userFile.close()
When using a program, a user is asked to create a username. Write a program that will ask a user to enter a username and check to see if it has already been used. Usernames are stored in a text file named ‘users’.
If it has already been used, the routine should inform the user and ask them to enter a new one. [8]
userName = input("Please enter a username.") userFile = openRead("users.txt") used = false
while NOT userFile.endOfFile() storedName = userFile.readLine() if storedName == userName then used = true endif endwhile userFile.close()
if used == true then
print(“Sorry this username has already been taken.
Please enter a new username.”)
endif