Computers and networks largely operate on the processing of data input and output.
I/O is the term we use when talking about these operations.
Types of I/O:
File system input/output is the process of reading and writing bits of data to areas of a physical hard drive.
Sometimes the flow of this data are known as streams.
Input - Reading data from a file into a program
Output- Writing data from a program into a file
Python has a basic file object that is available for basic file operations with no include.
To create a file object for an existing file:
file_obj = open("somefile.txt", "r")
r - Open in read mode
r+ - Open in read/write mode
w - Open in read mode
w+ - Open in both read/write mode
a - Open in append mode
a+ - Open in read/append mode
Once you have an open file you can read the contents of that file:
file_obj = open("somefile.txt", "r+")
data = file_obj.read(10)
file_obj.close()
You can also read lines from a file with a for loop:
file_obj = open("somefile.txt", "r+")
for line in file_obj:
print(line)
file.close()
DON'T FORGET TO CLOSE YOUR FILES!!!
Once you have an open file you can write data to that file:
file_obj = open("somefile.txt", "w+")
file_obj.write("SOME DATAZ!!!")
You can also append data to an open file:
file_obj = open("somefile.txt", "a+")
file_obj.write("I'm not DELETING DATAZ, I'm adding it...")
For working with directories and more advanced file and stream functions we have to import the os module.
import os
This will allow us to do things like move/rename a file and create a directory
import os
os.mkdir("secretz")
os.rename("file.zip", "secretz/file.zip")