跳过读取文件python中的空行 [英] Skipping Blank lines in read file python

查看:88
本文介绍了跳过读取文件python中的空行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个很长的项目,我已经完成了所有工作,但是在他希望我们在底部阅读的文件中,有空格,合法只是我们不允许删除的空格,以便工作在项目中我删除了它们,因为我不知道如何解决它,所以我当前的打开/读取看起来像这样

Im working on a very long project, i have everything done with it, but in the file he wants us to read at the bottom there are empty spaces, legit just blank spaces that we aren't allowed to delete, to work on the project i deleted them because i have no idea how to get around it, so my current open/read looks like this

      file = open("C:\\Users\\bh1337\\Documents\\2015HomicideLog_FINAL.txt" , "r")
 lines=file.readlines()[1:]
 file.close()

我需要添加什么来忽略空行?还是在遇到空行时停止?

What do i need to add to this to ignore blank lines? or to stop when it gets to a blank line?

推荐答案

您可以检查它们是否为空:

You can check if they are empty:

file = open('filename')
lines = [line for line in file.readlines() if line.strip()]
file.close()

这篇关于跳过读取文件python中的空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆