External Files Flashcards
What are some benefits of using external files?
Separation: cleaner and more modular code.
Reusability: Can be used across more than 1 file or program. Saves time and effort.
Memory management: Can be far more efficient (especially with larger data sets)
Collaboration: Makes it easier to work with other developers.
Try-except: What is else for?
Try should only contain code that may fail. Else contains what should happen normally.
Ways to open files.
open(filename, mode)
to close: filename.close()
with open(filename, mode) as name:
…
to close: done automatically
Modes of opening a file?
r - read
w- write
w+ or r+ - read and write
a - append
a+ - append and read
x - create*
t-text
b-binary
Difference between readline() and readlines()
.readline() reads a single line from a file (calling it more than once moves to different lines)
.readlines()
.read() reads the whole file
.strip()
removes whitespace (or as an argument, other characters)
using print() with files?
print(str, filename) writes the str to the file (this overwrites data)
writing to a file with .write()
.write(str) writes the str to the file. Remember newline characters.
making a new file?
open(new_file_name, w)
or
open(new_file_name,x)