Files and files and files.

--Originally published at Carolina's Blog Site

Opening Files

You can use Python to read and write the contents of files. Before a file can be edited, it must be opened, using the open function.

myfile = open(“filename.txt”)

The first argument of the open function is the path to the file (however, if the file is in the same directory as the program, you can specify only its name).

The second argument is the mode used to open a file.
“r” means open in read mode, which is the default.
“w” means write mode, for rewriting the contents of a file.
“a” means append mode, for adding new content to the end of the file.

Adding “b” to a mode opens it in binary mode, which is used for non-text files (like image and sound files).

Image result for meme binary
Btw, if you don’t recognize this, you really need to watch Pulp Fiction.

Once a file has been opened and used, you should close it.
This is done with the close method of the file object.

file.close()

Reading Files

The contents of a file that has been opened in text mode can be read using the read method. Here are some other methods:

>>> f.read()
'This is the entire file.\n'
>>> f.readline()
'This is the first line of the file.\n'
>>> f.readline()
'Second line of the file\n'
Or you can create a for loop:
>>> for line in f:
...     print(line, end='')

Other stuff

To write to files you use the write method, which writes a string to the file.

You should know, when a file is opened in write mode, the file’s existing content is deleted.

Image result for what why meme

Another way of working with files is using with statements. This creates a temporary variable (often called f), which is only accessible in the indented block of the with statement.with open(“filename.txt”) as f:

print(f.read())
The file is automatically closed at the end of the with statement, even if exceptions occur within it; this can save you a lot of problems.

Hope this was helpful!!

sources:

https://docs.python.org/3/tutorial/inputoutput.html

https://www.memecenter.com/fun/2363511/i-amp-039-m-losing-my-voice/comments