gpt4 book ai didi

python - 在 block 内使用 for 循环时如何格式化 Python

转载 作者:太空宇宙 更新时间:2023-11-04 08:33:36 24 4
gpt4 key购买 nike

我最近才开始使用 with 打开文件,而不是更老式的单独打开/关闭调用。

但是,我发现这意味着我所有遍历文件的代码现在都有双缩进:

with open('filename', 'rb') as f:
for line in f:
# do stuff

相比之下,这有点丑陋:

f = open('filename', 'rb')
for line in f:
# do stuff
f.close()

我试过:

with open('filename', 'rb') as f:
for line in f:
# do stuff

所以“东西”只是单缩进,但这让各种 lint 检查器提示。有没有更好的方法来处理这个问题?

注意:我很欣赏上下文管理器的额外好处,我只是在寻找格式化代码的最佳方式。

最佳答案

您不必将逻辑放在 with block 中:

with open('filename', 'rb') as f:
file_content = f.readlines()

for line in file_content:
# do stuff

这种方法的缺点是需要将整个文件保存到 file_content 列表中。

如果将读取逻辑隐藏在单独的函数中,您仍然可以享受生成器的好处:

def read_file(file_path):
with open(file_path, 'rb') as f:
for line in f:
yield line
# or simply `yield from f` in Python 3

for line in read_file(file_path):
# do stuff

但是 对于像两级缩进这样微不足道的事情,所有这一切可能都是大材小用。学会忍受它会更好。

关于python - 在 block 内使用 for 循环时如何格式化 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51019668/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com