繁体   English   中英

如何在 Python3 中的函数内迭代文件?

[英]How to iterate in a file inside a function in 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上的save_file ,但是当我调用它并尝试打印它们时,没有打印任何内容。

这是我调用的函数:

def find_min(file, threshold):

    with open(file, 'r') as f:
        reader = csv.reader(f)
        for i in reader:
            print(i)

如果我尝试在with语句之外调用find_min函数,则文件将正常迭代并打印出来。

但是我想多次调用这个函数来分析和压缩初始数据。

因此,没有人知道如何通过迭代save_filefind_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没有通过不读取整个文件find_min dest位于文件末尾,则必须在恢复写入之前调用dest.seek(0, 2)以确保我们首先位于文件末尾.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM