python-3.x - 如何在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
解决方案
当您有一个逻辑返回多个结果的函数时,您可以将其形成一个生成器,在该生成器中,您发送的每个结果都使用 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()
推荐阅读
- c# - 如何从asp项目中引用类库
- flutter - 如何在 Flutter 中成功加载 webview 之前显示本地图像?
- php - 下载存储为 BLOB 的图像不起作用
- angular - NgRX 效果 - 类型 'Observable
' 不可分配给类型 'Observable ' - javascript - UnhandledPromiseRejectionWarning:node_modules\snapdragon-util\index.js:282 拒绝 react-native 中的未处理承诺
- ruby - 如何解决此问题,当我尝试在本地系统上进行身份验证时,它工作正常,但是当上传到 heroku 时,它返回错误 500?
- php - 如何修复 local.ERROR:使用 Laravel 加载 cafile 流失败
- c++ - SFML:dyld:库未加载错误,即使库路径已更新
- android - 带有 ImageView 的 OnClick 按钮声音链接
- reactjs - 动态渲染自定义单选按钮组件