6) Reading and Writing Files

Reading and Writing Files

To open a file:

Let us look at the example first:

  • f = open(“mytxtfile.txt”, “w+”) ; Argument filename to operate on
  • Kind of access to give W write permission and +
    sign to create the file if it does not already exist

Read the file content:

contents = f.read() is used to read a file content.

Read the file line by line.

If your file is large it is not a good idea to read the whole file at once so we can read the file line by line. We use readlines for this Let us look at the example