我的代码是,
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 。有什么办法可以解决这个问题吗?编辑:我也尝试在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 .
最佳答案
在问题的代码中,数据通过 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)
关于python-3.x - 是否有办法刷新 csv 文件的数据而不实际关闭它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67138911/