File handling
Handling files
It is good practice to explicitly open a file, stating the mode of operation, before reading from or writing to it. This is written as follows:
OPENFILE <File identifier> FOR <File mode>The file identifier will be the name of the file with data type string. The following file modes are used:
READ for data to be read from the file
WRITE for data to be written to the file. A new file will be created and any existing data in the file will be lost.
A file should be opened in only one mode at a time. Data is read from the file (after the file has been opened in READ mode) using the READFILE command as follows:
READFILE <File Identifier>, <Variable>When the command is executed, the data item is read and assigned to the variable. Data is written into the file after the file has been opened using the WRITEFILE command as follows:
WRITEFILE <File identifier>, <Variable>When the command is executed, the data is written into the file. Files should be closed when they are no longer needed using the CLOSEFILE command as follows:
CLOSEFILE <File identifier>Example – file handling operations
This example uses the operations together, to copy a line of text from FileA.txt to FileB.txt
DECLARE LineOfText : STRING
OPENFILE FileA.txt FOR READ
OPENFILE FileB.txt FOR WRITE
READFILE FileA.txt, LineOfText
WRITEFILE FileB.txt, LineOfText
CLOSEFILE FileA.txt
CLOSEFILE FileB.txtreadline
file.readline([size])
f1 = open("a.txt", 'r')
content = f1.readline()
print(content) #Output first line of a.txt
f1.close()write
file.write(str)
f1 = open("a.txt", 'w')
f1.write('hello') #write hello to a.txt
f1.close()