python - 如果超过 x 个字符,如何从文件中删除行
问题描述
我怎么能做这样的事情?
with open(r'C:\some_list.txt') as f:
list = f.readlines()
for line in list:
if line: #has more than x characters
delete line
解决方案
如果文件相当小,最简单的方法是全部读入,过滤,然后全部写出。
with open(r'C:\some_list.txt') as f:
lines = f.readlines()
# Keep lines <= 10 chars long with a list comprehension
filtered_lines = [line for line in lines if len(line) > 10]
# Do what you like with the lines, e.g. write them out into another file:
with open(r'C:\filtered_list.txt', 'w') as f:
for line in filtered_lines:
f.write(line)
如果要将匹配的行流式传输到另一个文件中,那就更容易了:
with open(r'C:\some_list.txt') as in_file, open(r'C:\filtered_list.txt', 'w') as out_file:
for line in in_file:
if len(line) <= 10:
out_file.write(line)
推荐阅读
- flutter - 高尔夫应用程序获得高尔夫球场和发球台的平均分数
- css - 从自定义链接 onhover 中删除下划线
- python - BeautifulSoup 从一个标签中获取文本,但忽略另一个标签中的文本
- php - PHP: SimpleHTMLDom - 帮我获取 html 页面代码?
- node.js - 未在 Heroku 中注册的 Service Worker - Angular PWA
- python - 不知道这里出了什么问题,但猜测我需要更改路径
- bash - 在 Bash 中使用 AWS CLI 命令有什么不同吗?
- microsoft-graph-api - 访问 Intune Graph API 被禁止的错误
- javascript - 导出到 Excel 时如何以行格式显示项目数组?
- javascript - 在 Heroku 上本地运行的 React 应用程序崩溃:H10 “应用程序崩溃”