python - python - 如何在许多带有python的文本文件中删除以“1”开头的行
问题描述
我在目录中至少有 3700 个文本文件(实际上是标签)以及相同数量的 jpg/jpeg 图像。在所有这些文本文件中,有数百个具有如下文本:
1 0.19140625 0.50078125 0.3078125 0.9484375
我想在它存在的每个文本文件中从 1 开始删除这样的行。我尝试了以下操作:
import os
import glob
import errno
path = '~/Documents/txt/*.txt'
path1 = '~/Documents/txt/'
files = glob.glob(path)
txtfile = []
temp_path = os.path.join(path1, 'temp.txt')
for name in files:
try:
with open(name, 'r') as f, open(temp_path) as temp:
for line in f:
if line.strip() == "1":
continue
temp.write(line)
except IOError as exc:
if exc.errno != errno.EISDIR:
raise
#print(txtfile)
解决方案
import glob
import os
path = os.path.dirname(os.path.abspath(__file__))
for name in glob.glob(path+'/*.txt'):
raw_data = open(name, 'r')
data_list = raw_data.read().splitlines()
with open(name, "w") as new_file:
for row in data_list:
if row.startswith("1") is False:
new_file.write(row + '\n')
推荐阅读
- azure - 写入数据帧后 Spark 避免 hadoop fs.rename 失败
- rust - 变量的生存时间不足以通过通道发送
- javascript - 自动计算一些输入字段javascript
- php - 将自定义帖子类型“问题”的永久链接更改为帖子 ID
- python - Django:禁止直接分配到多对多集合的前端。改用 user.set()
- msbuild - WiX VS 项目,切换到 NuGet 包后 Heat 没有运行
- entity-framework - 避免实体框架中的重复键
- regex - 正则表达式删除第一个单词后的空格
- shapely - 为什么 MultiPolygon 的 MultiPolygon 小于其输入?
- c++ - 在另一台计算机上验证 Windows 访问令牌