我正在尝试编写一个jython代码来删除Text文件中的空格。我有以下场景。 我有一个像
这样的文本文件STARTBUR001 20120416
20120416MES201667 20120320000000000201203210000000002012032200000000020120323000000000201203240000000002012032600000000020120327000000000201203280000000002012032900000000020120330000000000
20120416MES202566 2012030500000000020120306000000000201203070000000002012030800000000020120309000000000201203100000000002012031100000000020120312000000000201203130000000002012031400000000020
20120416MES275921 20120305000000000201203060000000002012030700000000020120308000000000201203090000000002012031000000000020120311000000000201203120000000002012031300000000020120314000000000
END 0000000202
这里所有行都是单行。 但我想要的是
STARTBUR001 20120416
20120416MES201667 20120320000000000201203210000000002012032200000000020120323000000000201203240000000002012032600000000020120327000000000201203280000000002012032900000000020120330000000000
20120416MES202566 2012030500000000020120306000000000201203070000000002012030800000000020120309000000000201203100000000002012031100000000020120312000000000201203130000000002012031400000000020
20120416MES275921 20120305000000000201203060000000002012030700000000020120308000000000201203090000000002012031000000000020120311000000000201203120000000002012031300000000020120314000000000
END 0000000202
所以我想从第二行开始检查,直到我遇到END并删除每一行的所有空格。
有人可以指导我编写这段代码吗?
尝试过:
srcfile=open('d:/BUR001.txt','r')
trgtfile=open('d:/BUR002.txt','w')
readfile=srcfile.readline()
while readfile:
trgtfile.write(readfile.replace('\s',''))
readfile=srcfile.readline()
srcfile.close()
trgtfile.close()
谢谢, 马赫什
答案 0 :(得分:0)
您可以使用这些特殊行以特殊值开头的事实:
line = srcfile.readline()
while line:
line2 = line
if not line2.startswith('START') and not line2.startswith('END'):
line2 = line2.replace(' ','')
trgtfile.write(line2)
line = srcfile.readline()
另请注意,readline()
结果字符串以\n
结尾(或在输入文件末尾为空),此代码将删除行中的所有空格,而不仅仅是行末尾的空格
如果我理解你的例子你想要的只是删除空行,那么不要一行一行地读取文件:
content = srcfile.read()
然后从内容中删除空行:
while '\n\n' in content:
content = content.replace('\n\n', '\n')