def clearBlankLine():
file1 = open('text1.txt', 'r', encoding='utf-8')
file2 = open('text2.txt', 'w', encoding='utf-8')
try:
for line in file1.readlines():
if line == '\n':
line = line.strip("\n")
file2.write(line)
finally:
file1.close()
file2.close()
if __name__ == '__main__':
clearBlankLine()
有空行的文件:

运行代码生成无空行的文件:

可以使用 Python 的 os 模块来删除文件中的空行。
首先,使用 Python 的 open 函数打开文件,并将文件的内容读入到一个列表中:
with open('file.txt', 'r') as f:
lines = f.readlines()
s =’’
up_line_isKong = False
with open(path, ‘r’,buffering= 1073741824, encoding=‘utf-8’) as f:
for line in f:
content = re.sub(r'\n\s*\n', '\n', content)
with open('example_no_empty_lines.cpp', 'w') as file:
file.write(content)
在这个代码中,我们首先使用 `open()` 函数打开 cpp 文件,并用 `read()` 方法读取其中的内容。然后,我们使用正则表达式 `r'\n\s*\n'` 匹配所有连续的空行,并使用 `re.sub()` 函数将它们替换为空字符串。最后,我们将处理后的内容写入新的文件中。
请注意,这个代码只能去除完全为空的行。如果你想去除只包含空格或制表符的行,可以修改正则表达式为 `r'\n[ \t]*\n'`。