有没有办法在不实际关闭 csv 文件的情况下刷新它的数据?

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

我的代码是,

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)

最初它适用于并在第一个循环期间打印我文件中的所有内容。然后我输入新行“123”、“2021-04-18”,我什至尝试刷新它但是当我再次打印文件的内容时它没有显示。 output for the above code。有没有办法解决这个问题。 EDIT:I我也试过在 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)

输出可以是here.

在您 seek(0) 之后,您需要再次阅读该文件。现在您正在查看旧数据。

在问题的代码中,数据正在通过 mywriter 添加到 myfile1。因此我们需要刷新 myfile1 以使数据可用于 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)