Open File and Read All Content :
f = open("demofile.txt", "r")
print(f.read())
f.close()
Output :
[Contents of demofile.txt]
Open File Using Full Path and Read :
f = open("D:\\myfiles\\welcome.txt", "r")
print(f.read())
f.close()
Output :
[Contents of welcome.txt]
Read First 5 Characters from File :
f = open("demofile.txt", "r")
print(f.read(5))
f.close()
Output :
[First 5 characters]
Read First Line from File :
f = open("demofile.txt", "r")
print(f.readline())
f.close()
Output :
[First line of file]
Read Two Lines from File :
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
f.close()
Output :
[First line]
[Second line]
Loop Through File Line by Line :
f = open("demofile.txt", "r")
for x in f:
print(x)
f.close()
Output :
[All lines printed one by one]
Close File After Reading One Line :
f = open("demofile.txt", "r")
print(f.readline())
f.close()
Output :
[First line of file]