Press "Enter" to skip to content

Python Notes 4 : File Operations

Files

  • Opening a file in read mode
    • my_file = open(‘test.txt’)
  • Reading through the file
    • my_file.read()  (To read all the content)
    • my_file.readlines()    (readlines function returns a list of lines in the file)
  • Setting the cursor at a position in a file (This will set the cursor at position 0 in the file)
    • my_file.seek(0)
  • Writing to a text file
    • my_file = open(‘test.txt’,’w+’)
    • my_file.write(‘This is sample line inserted in file’)
  • iterating a text file line by line
    • for a in open(‘test.txt’)
      • print a
    • Above will print all the lines in the file, returning a line each time for loop is executed

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *