Is there anyway to flush data of a csv file without actually closing it?

Viewed 426

My code is,

import csv
myfile1=open('data1.csv','a')
mywriter=csv.writer(myfile1)
myfile=open('data1.csv','r+')
myreader=csv.reader(myfile)
for i in myreader:
    print(i)
mywriter.writerow(['123','2021-04-18'])
myfile.flush()
print('hello world')
myfile.seek(0)
for j in myreader:
    print(j)

initially it works well for and prints everything in my file during the first loop. Then i enter new row which is '123','2021-04-18' and i even tried flushing it but when i print the contents of the file again it doesn't show up. output for the above code. Is there anyway to solve this. EDIT:I've also tried reading again after seek(0),

import csv
myfile1=open('data1.csv','a')
mywriter=csv.writer(myfile1)
myfile=open('data1.csv','r+')
myreader=csv.reader(myfile)
for i in myreader:
    print(i)
mywriter.writerow(['123','2021-04-18'])
myfile.flush()
print('hello world')
myfile.seek(0)
myreader1=csv.reader(myfile)
for j in myreader1:
    print(j)

the output can be here.

2 Answers

In the code in the question, data is being added to myfile1 via mywriter. Therefore we need to flush myfile1 to make the data available to myfile.

import csv

myfile1 = open("data1.csv", "a")
mywriter = csv.writer(myfile1)
myfile = open("data1.csv", "r+")
myreader = csv.reader(myfile)
for i in myreader:
    print(i)
mywriter.writerow(["123", "2021-04-18"])

myfile1.flush()

print("hello world")
myfile.seek(0)
for j in myreader:
    print(j)

After you seek(0) you need to read the file again. Right now you are looking at old data.

Related