跳过读取文件python中的空行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40647881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Skipping Blank lines in read file python
提问by Brayden Hark
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?
我需要添加什么来忽略空行?或者在到达空行时停止?
回答by Fejs
You can check if they are empty:
您可以检查它们是否为空:
file = open('filename')
lines = [line for line in file.readlines() if line.strip()]
file.close()
回答by backtrack
for line in file:
if not line.strip():
... do something
Follwoing will be best for readinf files
以下将最适合 readinf 文件
with open("fname.txt") as file:
for line in file:
if not line.strip():
... do something
With open
will takecare of file close.
With open
将照顾文件关闭。
If you want to ignore lines with only whitespace
如果你想忽略只有空格的行
回答by 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)
回答by eshb
- 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. - Other way is to use
f.readline
instead off.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.
- 一种方法是使用
lines
列表并删除所有元素 e,使得 e.strip() 为空。这样,您可以删除所有带有空格的行。 - 另一种方法是使用
f.readline
代替f.readlines()
which 将逐行读取文件。首先,初始化一个空列表。如果当前读入行在剥离后为空,则忽略该行并继续阅读下一行。否则将读入行添加到列表中。
Hope this helps!
希望这可以帮助!