如何删除python文本文件中的空行?

如何删除python文本文件中的空行?,python,python-3.x,whitespace,removing-whitespace,blank-line,Python,Python 3.x,Whitespace,Removing Whitespace,Blank Line,在我的python脚本中,我将特定列从一个文本文件写入一个新的文本文件,由,分隔,因为新的文本文件稍后将成为一个csv文件。由于我跳过了需要从文件中删除的行,因此新的文本文件中还有空白行 我无法使用.strip()或.rstrip(),因为我得到错误:AttributeError:“\u io.TextIOWrapper”对象没有属性“strip” 我无法使用ip\u文件.write(“.”.join(如果不是line.isspace(),则在ip\u文件中逐行连接),因为我得到错误:不支持操作

在我的python脚本中,我将特定列从一个文本文件写入一个新的文本文件,由
分隔,因为新的文本文件稍后将成为一个csv文件。由于我跳过了需要从文件中删除的行,因此新的文本文件中还有空白行

我无法使用
.strip()
.rstrip()
,因为我得到错误:
AttributeError:“\u io.TextIOWrapper”对象没有属性“strip”

我无法使用
ip\u文件.write(“.”.join(如果不是line.isspace(),则在ip\u文件中逐行连接)
,因为我得到错误:
不支持操作:不可读

我还尝试导入了
sys
re
,并尝试了该站点上找到的所有其他答案,但仍然返回错误

我的代码是:

for ip in open("list.txt"):
    with open(ip.strip()+".txt", "a") as ip_file:
        for line in open("data.txt"):
            new_line = line.split(" ")
            if "blocked" in new_line:
                if "src="+ip.strip() in new_line:
                    #write columns to new text file
                    ip_file.write(", " + new_line[11])
                    ip_file.write(", " + new_line[12])
                    try:
                        ip_file.write(", " + new_line[14] + "\n")
                    except IndexError:
                        pass
生成的ip_文件如下所示:

, dst=00.000.00.000, proto=TCP, dpt=80
, dst=00.000.00.000, proto=TCP, dpt=80
, dst=00.000.00.000, proto=TCP, dpt=80

, dst=00.000.00.000, proto=TCP, dpt=80
, dst=00.000.00.000, proto=TCP, dpt=80
我是在上面脚本的最后一行,在循环中编码的。在我的脚本中,
new_text_文件
ip_文件
,所有内容都必须使用Python


<强>问题:< /强>是否有另一种方法来删除<代码> IPX文件< /代码>中的空行?或者阻止他们被写下来?

我想我理解你的意思。尝试进行以下更改:

        for line in open("data.txt"):
            new_line = line.rstrip().split()
                                    ^^^^^^^^^
            if "blocked" in new_line:
                if "src="+ip.strip() in new_line:
                    #write columns to new text file
                    ip_file.write(", " + new_line[11])
                    ip_file.write(", " + new_line[12])
                    try:
                        ip_file.write(", " + new_line[14])
            #                                                      ^^^^
                    except IndexError:
                        pass
                    ip_file.write("\n")
            #           

问题似乎是当
新行[14]
存在时,它已经包含了一个新行,所以您添加了两个新行。上述代码在拆分任何换行符之前将其从行中删除,然后在内部for循环的末尾添加一个换行符。

当您说“在
ip\u文件中删除空行”
”时,是否意味着“避免在
ip\u文件中写入空行”
?我不明白你的问题。你没有在任何地方读取
ip\u文件,因此我不知道你怎么会担心从中读取空行,而且你对
ip\u文件的所有调用。write
至少会在文件中写入一个逗号。那么你能澄清一下你的问题吗?@Brionius:我会再修改一下我的问题。嗯,这仍然会留下空白。您认为使用
.join()
可能有效吗?好的,尝试使用
split()
而不是上面提到的
split(“”
)。