添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
绅士的匕首  ·  windows: pip install ...·  2 天前    · 
酷酷的石榴  ·  SQL注入绕过技巧 - 简书·  2 年前    · 
好帅的丝瓜  ·  C++ for 循环 | 菜鸟教程·  2 年前    · 
# coding = utf-8
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'`。