Skip to main content
 首页 » 编程设计

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

2025年05月04日8lhb25

在我的 python 脚本中,我将特定的列从 text_file 写到 new_text_file,用 , 分隔,因为 new_text_file 稍后会变成 csv_file。 new_text_file 中遗留了空白行,因为我跳过了需要从文件中删除的行。

我不能使用 .strip() 或 .rstrip() 因为我收到错误:AttributeError: '_io.TextIOWrapper' object has no属性“剥离”。

我不能使用 ip_file.write("".join(line for line in ip_file if not line.isspace())) 因为我收到错误:UnsupportedOperation: not可读。

我还尝试导入 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_file 如下所示:

, 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_file 在我的脚本中是 ip_file 并且所有内容都必须使用 Python。

问题:有没有其他方法可以去除ip_file中的空行?或者阻止它们被写入?

请您参考如下方法:

我想我明白你在说什么。尝试进行这些更改:

        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") 
            #            

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