Skip to content

Instantly share code, notes, and snippets.

@adyliu
Created November 13, 2012 06:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adyliu/4064269 to your computer and use it in GitHub Desktop.
Save adyliu/4064269 to your computer and use it in GitHub Desktop.
fixed wordpress rss error with blank lines
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
#author: adyliu(imxylz@gmail.com)
#version: 0.1
import os
import os.path
import sys
DEBUG='--debug' in sys.argv
FIX ='--fix' in sys.argv
SUFFIX='.php'
ENCODING='utf-8'
if len(sys.argv) < 2:
print('Usage: [--debug] [--fix] <file>')
sys.exit(1)
def checkdir(filepath):
if DEBUG: print('check file',filepath)
if os.path.isdir(filepath):
for fname in os.listdir(filepath):
checkdir(os.path.join(filepath,fname))
if os.path.isfile(filepath) and filepath.endswith(SUFFIX):
fail=True
fixedmsg = ''
try:
lines=[]
with open(filepath,'r',encoding=ENCODING,errors='ignore') as f:
lines=f.readlines()
fail=len(lines)>0 and (len(lines[0].strip())==0 or len(lines[-1].strip()) ==0)
if fail and FIX:
start,end = 0,0
for i in range(len(lines)):
if len(lines[i].strip()) >0:
start = i
break
i=len(lines)
while i> 0:
if len(lines[i-1].strip()) >0:
end = i
break
i -= 1
with open(filepath,'w',encoding=ENCODING) as f:
for line in lines[start:end]:
if DEBUG: print(line)
f.write(line)
if DEBUG: print('write lines[%s:%s], total=%s'%(start,end,len(lines)))
fixedlines = start + len(lines) - end
fixedmsg = 'FIXED %s lines' % (fixedlines,)
finally:
if DEBUG or fail:
print(filepath,'=>','FAIL' if fail else 'OK',fixedmsg)
checkdir(os.path.abspath(sys.argv[-1]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment