M03 - Open and Read Files Flashcards
Text File
- Can be opened in a text editor like VS Code or Notepad
- CSV is a text file
- Data in text file is encoded as text using ASCII or Unicode
Binary File
- Contains data that has not been converted to text
- Cannot be opened with a text editor
General format for opening a file:
file_variable = open(‘filename’, ‘mode’)
Mode arguments in open( )
- ‘r’ opens a file to be read
- ‘w’ opens a file to write to it. This will overwrite an existing file and create a file if one does not already exist
- ‘x’ opens a file for exclusive creation. If it does not exist, it will not create one
- ‘a’ opens a file to append data to an existing file. If a file does not exist, it creates one, if a file has been created the data will be added to the file
- ’+’ opens a file for reading and writing
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
- When you read data from a file and it is not closed at the end, you can lose some of the data
- When you write data to a file, the data is not stored in the file at first. It’s written to a buffer in the memory and may be overwritten later if the file is not closed. Once closed, the data is stored
with statement
- replaces need to open( ) and close( ) every time
- with opens the file and ensures proper acquisition or release of any data without having to close the file, ensuring the data isn’t lost or corrupted
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
- Us to access files on different operating systems like macOS and Windows
- Contains several useful functions to make it easier to join a path
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
- Programmatic style that is used for making multiple method calls on the same object
- Common practice to make code look clean/concise
Indirect Path syntax
file_to_load = os.path.join(“FileName” , “file.ext”)