Wednesday, January 15, 2020

File Handling

Welcome Friends!

Being a programmer, it is important that we should be able to read and write data to a file. In today's blog, we will discuss how we can read and write to a file. 

There are various modes to open a file. For example:

  • w - to create a new file and write. If the file exists, it will overwrite it.
  • a - to append at the end of the file.
  • r - to read the file

Let's first create a new file
# Open a txt file with name as 'sample'
text_file = open('sample.txt', 'w')

for i in range(1, 10): 
    # Write to a file  
    text_file.writelines("Hello there! We are at line number {}\n".format(i))

# close the file
text_file.close()

To append the file, change the mode from "w"(write) to "a". 
# Open a txt file with name as 'sample'
text_file = open('sample.txt', 'a')

for i in range(1, 10): 
    # Write to a file  
    text_file.writelines("Hello there! We are at line number {}\n".format(i))

# close the file
text_file.close()

To read the file line by line, use the mode as "r".
# Open a txt file with name as 'sample'
text_file = open('sample.txt', 'r')

for each_line in text_file: 
    # Read to a file  
    print(each_line)

# close the file
text_file.close()


I hope you have enjoyed this. Stay tuned for more update.


No comments:

Post a Comment