Py Files Flashcards

1
Q

How to open a file?

What will happen if the file doesn’t exist?

A

]] f_name = open( )

– the file will be created if it doesn’t exist

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

how to close a file?

and, why does it make sense to close the file?

A

]] f_name = close( )

– since it will otherwise remain open in the ram memory

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are the possible parameter values when opening a file?

A

]] f_name = open( , ‘r’/ ‘w’/ ‘a’ )

– r: read, w: write, a: append

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How to create a new line in a file?

A

]] f_name.write ( ‘ text text text text text \n’

]] text text text text text text text text ‘ )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How to read a file’s content?

A

]] f_name.open( ‘file.name’, ‘r’ )

]] f_name.read ()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How to read one line from a file? which line?

How to read all lines from a file?

A

]] f_name.readline( ‘file.name’ )

]] f_name.readlines( ‘file.name’ )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

how to open, read all lines, print it and automatically close a file?

A

]] 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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

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?

A
    • cursor
    • in the beginning
    • at the end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

after one my_file.read(), how can you print out the content twice?
and, why is that needed?

A
-- 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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

how to create a new file and add a line to it?

what happens if a file with that name already exists?

A

]] 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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly