Today, we will discuss how to read and write files.
To read a file, we must first open it. To open it, we use the, well, open() function. Inside we provide two parameters. The first is the file name/path, and the other is the open permission, that is, whether we wish to read the file (r) or write the file (w).
After we get the file and store it in a variable, we use a for loop to go over each line in the file. We then do the most important part, we close the file. If we did not do it, we will get errors and bugs when reading and writing. Here is an example of reading a file:
The reason we use i.strip("\n") rather than i is because the print statement adds a new line to a sentence, even though there already is one. We use the strip command to remove the existing new line "\n" to avoid this.
To write to an existing file, we open the file using write permissions and use the write command to add text. Here is an example:
Note the \n characters. They are used to add new lines.
Here is the output:
Note that the write function overwrites the existing text. To prevent this, you can simply use "a" in place of "w".
To create a new file and add contents to it, nothing needs to be done. Yes, the program checks if the file exists, and if it does not exist, it creates a new one with that file name. Make sure that the permission is set to "a" or "w", though.
That is how we can manipulate files using Python.