Python Read File

The code below shows 2 ways to read file in Python.
1. Read all contents
2. Read line by line


#
# Python Read File
#

def main():  

  f = open("textfile.txt", "r")
  #1 Read contents
  if f.mode == "r":
    contents = f.read()
    print(contents)

  #2 Read line by line
  if f.mode == "r":
    fl = f.readline()
    for x in fl:
      print(x)
    
if __name__ == "__main__":
  main()


-------------------------------------------
#Output
This is a line 0

This is a line 1

This is a line 2

This is a line 3

This is a line 4

This is a line 5

This is a line 6

This is a line 7

This is a line 8

This is a line 9

This is a line 10

This is a line 11

This is a line 12

This is a line 13

This is a line 14

This is a line 0

This is a line 1

This is a line 2

This is a line 3

This is a line 4

This is a line 5

This is a line 6

This is a line 7

This is a line 8

This is a line 9

Comments

Popular posts from this blog

How to write to a file in Kotlin

Python Tkinter example