Skip to main content
 首页 » 编程设计

python之with ... : for . .. : 在一行中

2025年02月15日8jyk

<分区>

作为初学者 python 程序员,我希望这是一个有简单解决方案的愚蠢错误(或缺乏理解):

/tmp> python3 -c 'with open("t","r") as f: for l in f: print(l)' 
  File "<string>", line 1 
    with open("t","r") as f: for l in f: print(l) 
                               ^ 
SyntaxError: invalid syntax 

我可以在 oneline 中嵌入一个换行符,但试图理解为什么上面的方法不起作用

/tmp> python3 -c $'with open("t","r") as f:\n for l in f: print(l)' 
Hi there