python - Python中是否有任何快捷方式可以删除文件中每行末尾的所有空格?
问题描述
我了解到我们可以轻松删除文件中的空白行或删除每个字符串行的空白,但是如何删除文件中每行末尾的所有空白?
一种方法应该是处理文件的每一行,例如:
with open(file) as f:
for line in f:
store line.strip()
这是完成任务的唯一方法吗?
解决方案
不知道这些是否算作完成任务的不同方式。第一个实际上只是你所拥有的东西的变体。第二个是一次完成整个文件,而不是逐行。
在文件的每一行上调用“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
读取整个文件并使用 re.sub():
import re with open(filename) as f: text = f.read() text = re.sub(r"\s+(?=\n)", "", text)
推荐阅读
- android - 如何检测人像照片?
- facebook-messenger - 如何跟踪用户正在回答的问题?
- python-3.x - 如何使用 Python 在 tkinter Canvas 上的两个标签之间画线?
- ios - Firestore 不返回查询 Swift 5 Xcode 11.3
- mysql - 使用 Sequelize ORM 工具将导致较少问题的 Mysql 数据库列命名
- regex - 正则表达式:匹配除组之外的任何内容
- python - 删除不包含子字符串的行后如何返回数据框
- sql-server - 手动添加日期类型的表记录
- ios - SFSafariViewController 在导航栏和底部工具栏中是否始终具有相同的 UI 元素?
- c - Stack Paren Checker 在 C 代码中不起作用