Python File I/O
(eye oh)
What is I/O?
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.
- File System
- Network
Types of I/O:
File System Input/Output
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
Common I/O Operations
- Create a file/directory
- Write to a file
- Append to a file
- Rename a file
- Read the contents of a file
- Delete a file
File I/O using Python
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
Read a file using Python
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!!!
Write to a file using Python
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...")
Using the os module
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")
practice!
File I/O with Python
By Jason Sewell
File I/O with Python
- 1,841