Reading And Writing Files In Python

In this tutorial, we learn various techniques for reading and writing files in python.

Reading operation allows to read data from file and writing operation allows writing data into the. Python file objects provide various methods to perform this operation. Before understanding this operation we must need to know about file opening, file modes, and file objects.

Reading And Writing Files In Python

Writing Data Into a File

File Object has a method that allows writing data into the file. But before writing data into the file we need to open the file in write or append mode that allows us to write data into the file. If a file is opened into the write mode then old data is overridden by the new data. If we need to keep old data as it is and want to write new data then we must need to open the file in append mode.

Based on the data we need to decide the mode file in which we want to open the file. If we want to write binary data then we must need to open the file in binary write mode.

File Object provides the following two methods that help to write data into the file

  1. write(text): This method allows us to write data into the file. This method writes all the data on a single line. If want to write data on a separate line then we explicitly need to append a new-line ‘\n’ character. This method return number of character written into the file
  2. writelines(lines): This method allows us to write the list of lines into the file. In this line, separators are not added, so it is usual for each of the lines provided to have a line separator at the end.

Example

try:
    file=open("mydata.txt","w")
    file.write("Sunday");
    file.write("Monday");
    file.write("Tuesday");
finally:
    file.close()

After executing above code file contain below given data.

SundayMondayTuesday

So in above output we observe that all the data is written on same line. So we need to write each day on separate lines.

try:
    file=open("mydata.txt","w")
    file.write("Sunday\n");
    file.write("Monday\n");
    file.write("Tuesday\n");
finally:
    file.close()

After executing above code file contain below given data. That override old data and write new data into the file.

Sunday
Monday
Tuesday

So , now we want to append more day name into the file. so we open the file in append mode and use writelines method to write multiple in single call.

try:
    file=open("mydata.txt","a")
    days=['Wednesday\n','Thursday\n','Friday\n','Saturday\n']
    file.writelines(days)
finally:
    file.close()

After executing above code file contain following data.

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

After write data into the file, we must need to close the file otherwise changes are not reflected in the file permanently.

Reading Data From The File

File Object has a method that allows us to read data from the file. File object has the following methods to read data from the file.

  1. read(size=-1): This method helps us to read n characters from the file. If not provide any values as an argument then the whole file content is read and return.
  2. readline(): This method helps us to read one line from the file.
  3. readlines(hint=-1): This method helps us to read all lines into the list. The hint can be specified to control the number of lines read.

Example

try:
    file = open("mydata.txt");
    data = file.read();
    print(data)
finally:
    file.close()

Above code read the all the content of the file.

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
try:
    file = open("mydata.txt");
    data = file.read(20);
    print(data)
finally:
    file.close()

Above code helps us read 20 character from the file.

Sunday
Monday
Tuesda
try:
    file = open("mydata.txt");
    data = file.readline();
    print(data)
finally:
    file.close()

Above code helps us to read one line from the file.

Sunday
try:
    file = open("mydata.txt");
    data =f ile.readlines();
    print(data)
finally:
    file.close()

Above code helps us to read all line from file and return the list of lines.

['Sunday\n', 'Monday\n', 'Tuesday\n', 'Wednesday\n', 'Thursday\n', 'Friday\n', 'Saturday\n']

File Iterator

File object has an inbuilt iterator. That helps us to read data with the help of loop.

Example

try:
    file=open("mydata.txt");
    for f in file:
        print(f,end="")
finally:
    file.close()

In this example, we iterate the file object using for loop. At every iteration, one character read by the loop until not reach to file end. If we use the next() method to retrieve data in that case we reach at the end the generate StopIteration exception is generated

try:
    file=open("mydata.txt")
    while True:
            try:
                c=next(file)
                print (c,end="")
            except StopIteration:
                break
finally:
    file.close()

Above both code read the whole file content and print on screen.

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

For More Detail Refer Python Documentation

Leave a Comment

Your email address will not be published. Required fields are marked *