Opening & Closing a Text File
Output will be:
Following code is the classic way of opening and closing a text file.
1st line opens a file which is in the current directory and the other line closes the file.
Since the above way always needs the closing statement to close the file, the better Pythonic way of doing this is to use a context manager. A context manager is a construct that properly manages the setup and teardown of resources like files, network connections, or locks using the with statement.
Above code opens the file and save it in the memory as "f" and reads it and stores it in the variable called "output" and prints it out. Basically it prints the text file contents to the CLI.
Following is the sample.txt file in the working directory and let's run the above to see the output.
Output will be:
If we want to get the lines into a List,
Writing to a Text File
Following syntax will write a text to a file.
"w" implies that the file is opened to write, default it read only.
But this actually overwrites the file, so following will be the contents inside the file.
By proper spacing, using \n for line breaking, we can form the text much better.
Following example shows how we can write a file with List of data using f.writelines() method.
Output will be like the following..
Following sample code open 2 files and file and copy the contents of the source file to the destination file after manipulating the text. This is the advantage of copying it to memory. This example capitalizes the letters in the text.
Output will be:
Since forward slash (/) is used in Linux and back slash (\) is used in Windows, writing scripts to match the host OS can be problematic, Because of this, following piece of code helps to build the directory path according to the OS.