Py Files Flashcards
How to open a file?
What will happen if the file doesn’t exist?
]] f_name = open( )
– the file will be created if it doesn’t exist
how to close a file?
and, why does it make sense to close the file?
]] f_name = close( )
– since it will otherwise remain open in the ram memory
What are the possible parameter values when opening a file?
]] f_name = open( , ‘r’/ ‘w’/ ‘a’ )
– r: read, w: write, a: append
How to create a new line in a file?
]] f_name.write ( ‘ text text text text text \n’
]] text text text text text text text text ‘ )
How to read a file’s content?
]] f_name.open( ‘file.name’, ‘r’ )
]] f_name.read ()
How to read one line from a file? which line?
How to read all lines from a file?
]] f_name.readline( ‘file.name’ )
]] f_name.readlines( ‘file.name’ )
how to open, read all lines, print it and automatically close a file?
]] with open( ‘file.name’ , ‘r’ ) as my_file:
]] for in .readlines() :
]] print( my_file )
- with-file handler treats the filehandling as a separate
- block; assign to variable, close block at end of block
what’s the name of the functionality that reads through a file?
where is it at the start?
where is it after the my_file.read() has been applied?
- cursor
- in the beginning
- at the end
after one my_file.read(), how can you print out the content twice?
and, why is that needed?
-- save the file content to a variable ]] my_file.open( < file_name > ) ]] my_file_read = my_file.read( ) ]] print( my_file_read ) ]] print( my_file_read ) -- it is needed because the cursor is otherwise at the end of the filecontent
how to create a new file and add a line to it?
what happens if a file with that name already exists?
]] with open( “ .my_favourites “, “w” ) as my_file:
]] my_file.write( “my favourite tea is Earl Grey” )
– if the file already exists, it will overwritten