Text File
Binary File
- Cannot be opened with a text editor
General format for opening a file:
file_variable = open(‘filename’, ‘mode’)
Mode arguments in open( )
Open file, to read, w/ direct path
# Assign a variable for the file to load and the path file_to_load = 'file\path.ext'
# Open the file and read the file file_variable = open(file_to_load , 'r')
Close a file
file_variable.close( )
Important notes about closing a file
with statement
with statement syntax
with open(filename) as file_variable:
-file_variable is used to reference the file object through the script
with - open and print file data
# Assign a variable for the file to load and the path file_to_load = 'file\path.ext'
# Open the file with open(file_to_load) as file_data : (tab) print(file_data)
If we don’t know the direct path to the file, use which module?
os (operating system)
import os
os.path allows
os.path.join( )
-Joins our files path components together when they are provided as separate strings; then returns a direct path with the appropriate operating system separator (\ for windows or / for mac)
Chaining
Indirect Path syntax
file_to_load = os.path.join(“FileName” , “file.ext”)