Python File Methods

Python File Methods

This article contains all methods regarding opening, reading, writing and closing files

  1. close()

    • Closes the file

      f = open("demofile.txt", "r")
      print(f.read())
      f.close()
      
  2. detach()

    • Returns the separated raw stream from the buffer

      f = open("demofile.txt", "r")
      print(f.detach())
      
  3. fileno()

    • Returns a number that represents the stream, from the operating system’s perspective

      f = open("demofile.txt", "r")
      print(f.fileno())
      
  4. flush()

    • Flushes the internal buffer

      f = open("myfile.txt", "a")
      f.write("Now the file has one more line!")
      f.flush()
      f.write("...and another one!")
      
  5. isatty()

    • Returns whether the file stream is interactive or not

      f = open("demofile.txt", "r")
      print(f.isatty())
      
  6. read()

    • Returns the file content

      f = open("demofile.txt", "r")
      print(f.read())
      
  7. readable()

    • Returns whether the file stream can be read or not

      f = open("demofile.txt", "r")
      print(f.readable())
      
  8. readline()

    • Returns one line from the file

      f = open("demofile.txt", "r")
      print(f.readline())
      
  9. readlines()

    • Returns a list of lines from the file

      f = open("demofile.txt", "r")
      print(f.readlines())
      
  10. seek()

    • Change the file position
    f = open("demofile.txt", "r")
    f.seek(4)
    print(f.readline())
    
  11. seekable()

    • Returns whether the file allows us to change the file position
    f = open("demofile.txt", "r")
    print(f.seekable())
    
  12. tell()

    • Returns the current file position
    f = open("demofile.txt", "r")
    print(f.tell())
    
  13. truncate()

    • Resizes the file to a specified size
    f = open("demofile2.txt", "a")
    f.truncate(20)
    f.close()
    
    #open and read the file after the truncate:
    f = open("demofile2.txt", "r")
    print(f.read())
    
  14. writable()

    • Returns whether the file can be written or not
    f = open("demofile.txt", "a")
    print(f.writable())
    
  15. write()

    • Writes the specified string to the file
    f = open("demofile2.txt", "a")
    f.write("See you soon!")
    f.close()
    
    #open and read the file after the appending:
    f = open("demofile2.txt", "r")
    print(f.read())
    
  16. writelines()

    • Writes a list of strings to the file

      f = open("demofile3.txt", "a")
      f.writelines(["See you soon!", "Over and out."])
      f.close()
      
      #open and read the file after the appending:
      f = open("demofile3.txt", "r")
      print(f.read())
      

Did you find this article valuable?

Support BigSmoke's Blog by becoming a sponsor. Any amount is appreciated!