Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 使用python从文件中删除空行_Python 2.7 - Fatal编程技术网

Python 2.7 使用python从文件中删除空行

Python 2.7 使用python从文件中删除空行,python-2.7,Python 2.7,我正在尝试从文本文件中删除空行。以下是我对它的看法 aa=range(1,10) aa[3]="" print aa [1, 2, 3, '', 5, 6, 7, 8, 9] for i in range(0,len(aa)): if aa[i]=="": del aa[i] print lines [1, 2, 3, 5, 6, 7, 8, 9] 现在我尝试在文本文件上复制相同的方法来删除一个空行,但它不起作用 f=open("sample.txt",'r') li

我正在尝试从文本文件中删除空行。以下是我对它的看法

aa=range(1,10)
aa[3]=""
print aa
[1, 2, 3, '', 5, 6, 7, 8, 9]

for i in range(0,len(aa)):
    if aa[i]=="":
        del aa[i]
print lines
[1, 2, 3, 5, 6, 7, 8, 9]
现在我尝试在文本文件上复制相同的方法来删除一个空行,但它不起作用

f=open("sample.txt",'r')
lines=[]
for i in f:
    lines.append(i)

print lines
['In this 30th match\n', '\n', 'there will be no1 winner']

for i in range(0,len(lines)):
    if lines[i]=="":
        del lines[i]

print lines
['In this 30th match\n', '\n', 'there will be no1 winner']

您可以使用
if-line[i].isspace():
而不是
if-line[i]==”“:

范例

>>> 'hello'.isspace()
False
>>> '\n'.isspace()
True
这应该很好:

your_file=open("file_name.ext")
without_blanks=[x for x in your_file if not x.isspace()]
your_file.close()

for line in without_blanks:
    print line

首先,改变一个序列(从中删除元素),而迭代不是一个好主意

另外,您认为银行的行实际上不是空的,它可能包含一些空格、制表符(,或其他)字符,但是(如打印
变量时所见),它将包含一个EOLN标记:
\n
(或
\r\n
)在Windows上

因此,您可以在首次打印行后修改代码,执行以下操作:

lines[:] = [item for item in lines if item.strip()]

如果len(lines[i].rstrip())小于1:del lines[i]请检查以下链接:,,谢谢ForceBru,isspace()运行良好。现在还有一个问题。一旦删除一行,列表项的索引将更改,并返回索引超出范围错误。例如:删除第二行。第三行会取第二行的索引,当循环到达最后一次迭代时,它将不存在删除的行数。我猜想,你是用C或C++的方式在列表中重复的,我想。在Python中,应该使用
对iterable:
中的某些内容进行迭代。请查看我编辑过的答案。谢谢ForceBru,isspace()运行良好。现在还有一个问题。一旦删除一行,列表项的索引将更改,并返回索引超出范围错误。例如:行=[1',3,5',23]删除第二项。第三项将采用第二项的索引,当循环到达最后一次迭代时,它将缺少删除的行数。我想不删除空白行,但只做一个新的名单,非空白行。还有其他建议吗?@Abacus,当然,我已经编辑了我的答案,请检查一下。嘿,ForceBru,你的方法很酷。谢谢。就个人而言,我喜欢反复浏览列表的索引,这有助于我更清楚地看到循环。谢谢CristiFati,你的建议非常有用。