Python Basics NOTES 3 File Handling

= open("tejas.txt",'rt')
content = f.read()
print(content)
content = f.read()  # blank argument for all content
print(content)

f.close() 

# reading by iteration :
for line in f:
    print(line, end="")
"""
Every line has a EOF character thats why it will give a line space after raeding every line.

By default "end" has value of EOF thats why it puts '\n' after raeding "\n" from the line and provides a line space. By making end="" it takes value "".

After reading, file pointer becomes empty we cant use it again. (2 & 11 code line cant be executed together)

"""
    
# for reading line by line :
= open("tejas.txt")
print(f.readline(),end="")
print(f.readline(),end="")
print(f.readlines(),end="")   #all lines
f.close()


# writing to a file :
= open("tejas.txt",'a')
= f.write("Harry bhai bahut achee hai...\n")
print(f"The number of characters written : {a}")
f.close()

# r+ (read and write mode) :
"""
f = open("tejas.txt",'r+')
print(f.read())
f.write("Thanks for writing to our file\n")
print(f.read())
f.close()
"""

= open("tejas.txt",'r')
print(f.read())
print(f.readlines())

print(f.tell()) 
f.seek(0)   #initialize cursor at 0 and make read() to work again
print(f.read())   
f.close()

# with block :
with open("tejas.txt",'w'as f:
    f.next()
    f.write("This data has been overwritten")
    
with open("tejas.txt",'rt'as f:
    print(f.read())
    



Comments

Popular Posts