首页 > 解决方案 > 无论如何要刷新csv文件的数据而不实际关闭它?

问题描述

我的代码是,

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'的新行,我什至尝试刷新它但是当我再次打印文件的内容时它没有显示出来。 上述代码的输出。有没有办法解决这个问题。编辑:我也尝试在 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)

输出可以在这里

标签: python-3.xcsvflush

解决方案


在问题的代码中,数据被添加到myfile1via mywriter。因此,我们需要刷新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)

推荐阅读