如何在Python3中的函数内的文件中进行迭代?
我有这个功能,我打开两个文件,一个用于读取,一个用于写入。我遍历如何在Python3中的函数内的文件中进行迭代?,python,file,stream,iteration,Python,File,Stream,Iteration,我有这个功能,我打开两个文件,一个用于读取,一个用于写入。我遍历input\u文件,并将其中的一些项目写入save\u文件 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: #d
input\u文件
,并将其中的一些项目写入save\u文件
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_文件
上的项,但是当我调用它并尝试打印它们时,不会打印任何内容
这是我调用的函数:
def find_min(file, threshold):
with open(file, 'r') as f:
reader = csv.reader(f)
for i in reader:
print(i)
如果我尝试使用语句在之外调用find_min
函数,文件将正常迭代并打印
但是我想多次调用这个函数来分析和压缩初始数据
那么,是否有人知道如何在find\u min
函数中迭代save\u file
。问题是您没有关闭输出文件(或将其内容刷新到磁盘),因此在关闭之前无法可靠地读取它。解决方案是使用flagw+
打开文件进行写入和读取:
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)
必须在恢复写入之前进行,以确保我们首先定位在文件的末尾。如果您可以将写入文件的所有数据保存到内存中(列表中),那么最好在该列表上进行迭代。打开文件进行写操作并不保证在文件关闭之前任何内容都会被实际写入。我不想创建一个列表,因为它会降低整个程序的速度,但对文件的迭代肯定会比对列表的迭代慢。我同意,但因为我处理的是大文件,我不想让内存过载