首页 > 解决方案 > Python中是否有任何快捷方式可以删除文件中每行末尾的所有空格?

问题描述

我了解到我们可以轻松删除文件中的空白行或删除每个字符串行的空白,但是如何删除文件中每行末尾的所有空白?

一种方法应该是处理文件的每一行,例如:

with open(file) as f:
  for line in f:
    store line.strip()

这是完成任务的唯一方法吗?

标签: python

解决方案


不知道这些是否算作完成任务的不同方式。第一个实际上只是你所拥有的东西的变体。第二个是一次完成整个文件,而不是逐行。

  1. 在文件的每一行上调用“rstrip”方法的映射。

    import operator
    
    with open(filename) as f:
    
        #basically the same as (line.rstrip() for line in f)
        for line in map(operator.methodcaller('rstrip'), f)):
    
            # do something with the line
    
  2. 读取整个文件并使用 re.sub():

    import re
    
    with open(filename) as f:
        text = f.read()
        text = re.sub(r"\s+(?=\n)", "", text)
    

推荐阅读