def delblankline(infile, outfile): infopen = open(infile, 'r',encoding="utf-8") outfopen = open(outfile, 'w',encoding="utf-8") lines = infopen.readlines() for line in lines: if line.split(): outfopen.writelines(line) else: outfopen.writelines("") infopen.close() outfopen.close() delblankline("jb51.txt", "o.txt")
# -*- coding: utf-8 -*-
python读取文件,将文件中的空白行去掉
def delblankline(infile, outfile):
    infopen = open(infile, 'r',encoding="utf-8")
    outfopen = open(outfile, 'w',encoding="utf-8")
    lines = infopen.readlines()
    for line in lines:
        line = line.strip()
        if len(line)!=0:
            outfopen.writelines(line)
        outfopen.write('\n')
    infopen.close()
    outfopen.close()
delblankline("jb51.txt", "o2.txt")
可以使用 Python 的 os 模块来删除文件中的空行。 首先,使用 Python 的 open 函数打开文件,并将文件的内容读入到一个列表中: with open('file.txt', 'r') as f: lines = f.readlines()
# coding = utf-8 def clearBlankLine(): file1 = open('text1.txt', 'r', encoding='utf-8') # 要 去掉 的文件 file2 = open('text2.txt', 'w', encoding='utf-8') # 生成没有空行的文件 for line in file1
output_file_path = 'cleaned_output_file.xlsx' df_cleaned.to_excel(output_file_path, index=False) 此方法会创建一个新的不含任何全空行的工作表[^1]。 #### 方法二:利用 OpenPyXL 库逐行遍历工作簿并手动删除 空白行 对于更复杂的场景或者当需要保留原始文件结构时,OpenPyXL 是更好的选择。这种方法允许精确控制哪些行应该被标记为“ 空白 ”。 ``` python from openpyxl import load_workbook wb = load_workbook('F:\\ python _study\\表格\\插入行列.xlsx') sheet = wb.active rows_to_delete = [] for row in sheet.iter_rows(min_row=1, max_col=sheet.max_column, max_row=sheet.max_row): if all(cell.value is None for cell in row): # 如果整行都是None,则认为该行为 空白行 rows_to_delete.append(row[0].row) # 反向迭代以避免影响后续要检查的行号 for row_num in reversed(rows_to_delete): sheet.delete_rows(idx=row_num) wb.save('F:\\ python _study\\表格\\无 空白行 的文件.xlsx') 这段 代码 通过反向循环删除找到的所有 空白行 ,从而防止因修改文档而引起的索引错误[^2]。 两种 方式都可以有效地清理 Excel 表格内的多余 空白行 ,具体采用哪种取决于实际需求以及对原文件格式的要求。