Lesson 11 Flashcards
Limitations to imputing data into Python
It would be very tedious to use terminal screen arguments or input() prompts for large amounts of data.
Data is often transferred as files (a self contained collection of data)
To open a file in python use
open() function which takes the filename as a string and an optional mode argument.
Mode “r”
Read default- open for reading, error if file does not exist
Mode “a”
Append open for appending, creates file if it does not exist. File pointer starts at the end of the file
Mode “w”
Write- open for writing created file if it does not exist. Deletes all existing data in file
Mode “x”
Create file and open for writing. File Exists Error if file exists.
Mode “r+”
Read/write open file for reading and writing
Two necessary things about opening a file
1) the file needs to be in the same directory as your current directory in the terminal, or it needs to contain the path to the file.
In this course, we are only learning how to handle text files
read(<opt.>)</opt.>
Returns all the text in the file. Optional argument used to specify how many characters to read. Move the file pointer to the next unread character. File must be opened in “r “ mode
Readline()
Returns all the text up to and including the next new line character (\n) move the file to the pointer to the start of the next line. File must be opened in “r” mode.
Close()
Close the file, which you should always do to avoid python, locking the file or not writing all the data to the file
Write(<str>)</str>
Write a string to the file. File must be opened in “a” or “w” mode