底部是我通常解析 TXT 文件的方式(工作正常!)
我的问题:有没有一种更优雅/Pythonic/最佳实践的方式来获取
[line.strip()
for line in file.readlines()
if line.strip()]
### create a sample TXT file for demo
with open('recipe.txt', 'w') as file:
file.write("""
3 oeufs
180 g de sucre
le zest de 2 citrons
""")
### parse the sample TXT file
with open('recipe.txt', 'r') as file:
lines = [line.strip()
for line in file.readlines()
if line.strip()]
# ['3 oeufs', '180 g de sucre', 'le zest de 2 citrons']
最佳答案
您可以使用walrus operator (assignment expressions)在 python 3.8 中将 strip 保存到变量中,然后使用它
[x for line in file.readlines() if (x := line.strip())]
关于python - 在Python中解析TXT文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71673884/