This is down to changes that were made for new versions of ZPE.
File operations are one of the most common features of programming languages. Python, like many other scripting syntaxes, simplifies the method in which files are used. This article discusses both reading and writing files.
Before a file can be written to or read from it must first be opened.
wmode for instance it will not exist and thus cause an error when trying to write to it. When a file is opened with the
w+mode it will create the file first and then open it.
Once a file is finished with it should be closed.
The following table shows the read modes that can be used:
|r||Open an existing file for standard reading|
|r+||Opens a file for standard reading and writing|
|w||Opens an existing file for standard writing|
|w+||Opens a file for standard reading and writing. Also if the file does not exist, it attempts to create it.|
|a||Opens an existing file for writing with the file pointer at the end of the file.|
|a+||Opens a file for reading and writing with the file pointer at the end of the file.|
These modes are used in conjunction with the
# Open the file test.txt in read mode, if it doesn't exist then create it file = open("test.txt", "r+") file.close()
Now that the file is open the next step is to read it.
Python provides a very simple method of reading text files using the
read chained method:
# Open the file test.txt in read mode file = open("test.txt", "r") print(file.read()) file.close()
Writing to a text file couldn't be simpler in Python. Once the file object
has been opened it is simple enough to just write to it using the
write chained method:
# Open the file test.txt in write mode file = open("test.txt", "w+") file.write("Test text") file.close()
This will write just one line of text. To write multiple lines a Python list
is used to hold those lines and the
writelines method is used instead:
# Open the file test.txt in write mode lines = ["Test 1", "Test 2"] file = open("test.txt", "w+") file.writelines(lines) file.close()
S1s and S2s really enjoyed the lesson on cybercrime using the lesson on How to Rob A Bank on… https://t.co/MxjDYE2JFu
7 months ago
S2s doing really well in hardware test! Also really enjoying doing tests electronically rather than on paper.… https://t.co/ritdfcW6Mw
7 months ago
S1 and S2 pupils listing input and output devices and giving answers such as keyboard and mouse but there were also… https://t.co/dGxDkYqFxo
7 months ago