Comp Sci Study Notes
Comp Sci Study Notes
EXTRA:
If you forget any, type help(str) to list all the methods available
Add all your built-in functions into main( ), In the proper order;
Def main( ):
instructions( )
Startgame ( )
Playagain ( )
then end the program with to make sure code runs smoothly
If__name__ == “__main__”:
main( )
If you want python to input all the aspects of a module add a “ * “ (sometimes its redundant and doesn’t work
properly don't always add it)
OR To close the file automatically when we’re done modifying just add “with” before it! As a function
↳ with open(filename, mode) as file:
then add code below this as normal the same way you would a built in function
Can also do this to open multiple files at a time and using different modes
with open(f.txt, ‘r’) as f, open(h.txt, ‘w’) as h:
Info = f.readlines( )
for line in Info:
h.write( line.strip.lower() + ‘\n’ )
#this reads file f.txt and writes in the same data into file h.txt then automatically closes both programs when done
#h.write( line.strip.lower() + ‘\n’ )
Different types of modes:
- Reading: ‘r’ as mode, reads the file in the parameter starting from the top down
Different types of reading modes
1. f.read( ), reads and returns the entire file data
2. f.readlines( ), reads and returns the entire file data as a list however includes “\n”,
will have to list.pop( ) test this
3. f.readline( ), reads and returns only the following line with “\n”
WILL print an empty string if the next line is the end of the file (therefore there’s no data)
To avoid this add:
line = file.readline( )
While line != “ “
print(line)
line = file.readline( )
file.close( ) ⟶ closes the file and ends session once read mode reaches the end of the file
Read the entire file (not line by line) with a for loop:
for line in file:
print(line)
file.close( )
- Writing: ‘w’ as mode, creates a new file for writing, if file in input already exists it deletes it and restarts
use f.write( ) , if you want it to write on a new line add \n
f.write(“Hi how are you\n”)
- Appending: ‘a’ as mode, creates a new file for writing, if file in input already exists it adds data at the
bottom