python-3.x - 无论如何要刷新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)
输出可以在这里。
解决方案
在问题的代码中,数据被添加到myfile1
via 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)
推荐阅读
- php - 与 Scribunto Mediwiki Infobox 相关的 Lua 错误
- .htaccess - htaccess RewriteRules 奇怪的行为
- python - ValueError:应提供一个非空的瓦片列表以进行合并
- ruby-on-rails - 使用 rails 在 pdf 文件中搜索单词
- pyspark - 使用更改日志装饰器时如何写回输出数据帧?
- sql - 使用 as.data.frame 在 Spark 中的 R 中创建数据框时出错
- c# - 如何确定在 .net 核心中使用 httpclient 协商了哪个 TLS 版本?
- aws-lambda - 添加 disableLogs: true 将返回“发生错误:IamRoleLambdaExecution - 策略语句必须包含资源”
- azure - 未找到与 D:\build\V1\_w\1\s\test\target\reports\*.xml 匹配的测试结果文件
- python - 错误 tkinter 窗口