python - 在Python中解析TXT文件

标签 python list io list-comprehension

底部是我通常解析 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/

相关文章:

c++ - 图像写入功能未执行

javascript - HTML5异步文件上传,上传流总是无效

python - 根据条件对数据帧进行排序,并通过动态分配给随机向量来返回所有组

python - 如何在没有双引号的情况下修复 JSON 键值?

python - Flask-SQLAlchemy 如何删除单个表中的所有行

带有列表参数的 Python sum() 函数

python - 如何找出列表列表中是否有重复项

python - 使用 Python 在 json 模式中完全扩展 $ref 引用

python - 检查项目是否在列表中的最快方法 - Python

java - Logback 文件附加程序不会立即刷新