Basic File Handling Operations Flashcards

1
Q

Opening a text file -

  • When opening a text file in Python we use the open command.
  • This tells our program that we want to open (or create if it doesn’t already exist) a text file with the name we give it.
  • We also must tell the program what mode we want to open the text file in:
A
  • r = Read mode.
  • Opening a text file in this mode means you cannot make any changes to the text file, only read it.
  • w = Write mode.
  • Opening a text file in this mode means you can make changes to the text file, however the current contents will be erased and overwritten.
  • a = Append mode.
  • Opening a text file in this mode means you can make changes to the text file, and add new data to the end of the text file, without erasing what is already there.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Example of opening a text file (read mode) -

  • In the example below we are opening a text file called ‘CustomerDetails’ in read mode.
  • For the purpose of this example the text file has already been created and populated with some data.
  • We have then outputted the contents of the text file and closed the text file.
A
  • file_data = open(“CustomerDetails.txt”, “r”)
  • print(file_data.read())
  • file_data.close()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly