首页 > 解决方案 > 如何在python中使用for循环打开文件

问题描述

所以这个函数的目的是测试我的文件夹中的所有文件。我想遍历 for 循环并测试每个文件,但我的问题是我的 return 语句只返回最后一个文件进行测试。我需要它遍历所有文件并为每个文件返回答案,而不仅仅是一个。我很困惑,我是一个初学者程序员,所以任何帮助将不胜感激,谢谢!

这是我定义的函数:

def testFileOpener():
    files = ['maze.txt','maze50100.txt','maze1020.txt','maze510nosoln.txt','maze510islandnosoln.txt','maze510island.txt','maze510cycles.txt','maze510.txt']
        
    for file in files:
        try:
            print(f'Testing {file}\n')
            f = open(file)
            mazeFiles = f.readlines()
            
        except:
            print('This File Does Not Exist.')

            
    f.close()
    return mazeFiles

我的测试功能如下所示:

def test():
    mazeFiles = testFileOpener()
    m = Maze(mazeFiles)
    m.gridAssembly()
    m.solver(0,0,None)
    m.tester()

输出应该看起来像:

测试迷宫.txt

-这行代码应该是每个maze.txt的返回行-

测试迷宫50100.txt

-这行代码应该是每个maze50100.txt的返回行-

...每个文件都被传递到测试 mazeFiles 的测试器中,因此在每个实例中 mazeFiles 必须是不同的“.txt”文件

等等......直到我们到达最后一个文件,但由于某种原因它到达最后一个文件,并且 mazeFiles 只返回该特定文件行。

任何帮助将不胜感激

我试过了:

def testFileOpener():
    files = ['maze.txt','maze50100.txt','maze1020.txt','maze510nosoln.txt','maze510islandnosoln.txt','maze510island.txt','maze510cycles.txt','maze510.txt']
    random = []   
    for file in files:
        
        print(f'Testing {file}\n')
        with open(file) as f:
            d = f.readlines()
            random.append(d)
    for i in random:
        mazeFiles = i
    return mazeFiles

标签: python-3.xlistfunctionfileclass

解决方案


当您有一个逻辑返回多个结果的函数时,您可以将其形成一个生成器,在该生成器中,您发送的每个结果都使用 ayield而不是 a return。所以您的代码可能如下所示:

def testFileOpener():
    files = ['maze.txt','maze50100.txt','maze1020.txt','maze510nosoln.txt','maze510islandnosoln.txt','maze510island.txt','maze510cycles.txt','maze510.txt']
    for file in files:
        print(f'Testing {file}\n')
        with open(file) as f:
            d = f.readlines()
            yield d # note that you can actually just `yield f` if you deal with each one sequentially
                    # since the file only gets closed after the next iteration
                    # this is one of the benefits of using a generator.

然后这个函数的调用者可能想要遍历结果:

def test():
    for mazeFiles in testFileOpener():
        m = Maze(mazeFiles)
        m.gridAssembly()
        m.solver(0,0,None)
        m.tester()

推荐阅读