如何解决如何在Python3中的函数内的文件中进行迭代?
我具有此功能,可以打开两个文件,一个用于读取,一个用于写入。我遍历input_file
,并将其中的一些内容写到save_file
。
with open(input_file,'r') as source,open(save_file,'w') as dest:
reader = csv.reader(source)
writer = csv.writer(dest)
for row in reader:
#do_something
find_min(save_file,threshold)
尽管通过迭代,我想调用另一个函数并遍历我附加在save_file
上的项目,但是当我调用它并尝试打印它们时,什么也不会打印。
这是我称之为的功能
def find_min(file,threshold):
with open(file,'r') as f:
reader = csv.reader(f)
for i in reader:
print(i)
如果我尝试在find_min
语句之外调用with
函数,则文件将正常进行迭代并被打印。
但是我想多次调用此函数,以便分析和压缩初始数据。
因此,没有人知道如何在save_file
函数中的find_min
中进行迭代。
解决方法
问题是您尚未关闭输出文件(或将其内容刷新到磁盘),因此直到关闭输出文件后,才能可靠地读取它。解决方案是使用标志w+
打开文件以进行读写:
with open(input_file,'r') as source,open(save_file,'w+') as dest:
然后传递到find_min
dest
:
find_min(dest,threshold)
# make sure we are once again positioned at the end of file:
# probably not necessary since find_min reads the entire file
# dest.seek(0,2)
def find_min(dest,threshold):
dest.seek(0,0) # seek to start of file for reading
reader = csv.reader(dest)
for i in reader:
print(i)
# we should be back at end of file for writing,but if we weren't,then: dest.seek(0,2)
如果find_min
没有通过不读整个文件而使dest
留在文件末尾,则必须先调用dest.seek(0,2)
,然后才能继续写入确保我们首先位于文件末尾。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。