Skipping Blank lines in read file python

天涯浪子 提交于 2019-12-05 16:56:53
for line in file:
  if not line.strip():
    ... do something

Follwoing will be best for readinf files

with open("fname.txt") as file:
    for line in file:
      if not line.strip():
        ... do something

With open will takecare of file close.

If you want to ignore lines with only whitespace

You can check if they are empty:

file = open('filename')
lines = [line for line in file.readlines() if line.strip()]
file.close()
  1. One way is to use the lines list and remove all the elements e such that e.strip() is empty. This way, you can delete all lines with just whitespaces.
  2. Other way is to use f.readline instead of f.readlines() which will read the file line by line. First, initialize an empty list. If the present read-in line, after stripping, is empty, ignore that line and continue to read the next line. Else add the read-in line to the list.

Hope this helps!

Inconnu

Here's a very simple way to skip the empty lines:

with open(file) as f_in: 
    lines = list(line for line in (l.strip() for l in f_in) if line)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!