鉴于填充物包含:
aaaaaaa"pic01.jpg"bbbwrtwbbbsize 110KB
aawerwefrewqa"pic02.jpg"bbbertebbbsize 100KB
atyrtyruraa"pic03.jpg"bbbwtrwtbbbsize 190KB
如何获得输出文件:
pic01.jpg 110KB
pic02.jpg 100KB
pic03.jpg 190KB
我的代码是:
with open ('test.txt', 'r') as infile, open ('outfile.txt', 'w') as outfile:
for line in infile:
lines_set1 = line.split ('"')
lines_set2 = line.split (' ')
for item_set1 in lines_set1:
for item_set2 in lines_set2:
if item_set1.endswith ('.jpg'):
if item_set2.endswith ('KB'):
outfile.write (item_set1 + ' ' + item_set2 + '\n')
但是代码生成了一个空白文件。怎么了??你知道吗
无需导入
re
的解决方案。该条件可以改进为单线条件。你知道吗您的代码只有一个主要问题:
if item_set2.endswith ('KB')
检查不起作用,因为每行末尾都有一个新行字符。替换为(注意strip()
调用):另外,您不需要
+ '\n'
,因为item_set2
已经在末尾包含了新行:仅供参考,您可以将regex与保存组一起使用来提取数据:
运行代码后
outfile.txt
的内容:您应该使用regex,这将简化您的代码。比如:
你知道吗输出文件.txt此脚本返回:
相关问题 更多 >
编程相关推荐