Python : Basics of File Handling

python

In this tutorial we will be showing how to work with files stored in the host, such as reading the contents of the file, adding more lines, etc.

Listed below are few of the syntax used in Python to work with files. We will be using them in the Python scripts posted later:

  • Open file in read mode
    theFile = open(‘myFile.txt’, r)
  • Open file in append mode
    theFile = open(‘myFile.txt’, a)
  • Open file in write mode
    theFile = open(‘myFile.txt’, r+)
  • Read the entire file
    theFile.read()
  • Read 4 bites of the file
    theFile.read(4)
  • Read file line by line
    theFile.readline
  • Read all lines in the file to a list
    theFile.readlines
  • Write string to a file
    theFile.write(<string>)
  • Closes the conenction to a file
    theFile.close()

Let us work with the files now:

  • Now let us create a simple text file with the following content:
    [root@gw16-lap-devops webapp]# cat sample.txt
    Line 1
    Line 2
    Line 3
    Line 4
    Line 5
    Line 6
    Line 7

 

  • Let us write a Python script to read and print the contents of the file:
    [root@gw16-lap-devops webapp]# cat readFile.py
    #! /usr/bin/python
    #
    myFile = open(“sample.txt”)
    print(myFile.read())
    myFile.close()

 

  • Now if you run the file you will see the entire contents getting displayed.
    See if you can use the “myFile.read(8)” command in it and check the result.

Let us write a Python script to write a line to the same file and then read and print the contents of the file:

  • [root@gw16-lap-devops webapp]# cat writeLines.py
    #! /usr/bin/python
    #
    theFile = open(“sample.txt”,’a’)
    theString = ‘\nAdding a line’
    theFile.write(theString)
    theFile.close()
    #
    myFile = open(“sample.txt”)
    print(myFile.read())
    myFile.close()

Let us write a Python script to write a line to the same file and then read and print the contents of the file:

  • [root@gw16-lap-devops webapp]# cat writeLines.py
    #! /usr/bin/python
    #
    theFileName = ‘sample.txt’
    myFile = open(theFileName)
    theFileList1 = myFile.readlines()
    myFile.close()
    totalLines=len(theFileList1)
    #
    #
    theFile = open(theFileName,’a’)
    lineNo = totalLines + 1
    for i in range(3):
    theString = “Line ” + str(lineNo) + “\n”
    theFile.write(theString)
    lineNo = lineNo + 1
    theFile.close()
    #
    #
    myFile1 = open(theFileName)
    print(myFile1.read())
    myFile1.close()