本文實例講述了python去除檔案中空格、Tab及回車的方法。具體如下:
服務端的json檔案都是人工寫的,寫完之後發現格式都是十分規整,易於人閱讀的json,但是客戶端請求不需要那些為了格式而在json裡面添加的空格、tab、回車等等沒用的字符,遂用python寫一腳本,去除文件中的空格、回車、換行。
原始json檔案:
{ "amount" : "2", "content" : [ { "category_id" : 0, "name" : "古典文学", "category_json_url" : "http://172.16.242.14:8080/source/history/history.json" }, { "category_id" : 1, "name" : "流行音乐", "category_json_url" : "http://172.16.242.14:8080/source//popmusic/popmusic.json" } ] }
用腳本處理後的檔案:
{"amount":"2","content ":[{"category_id":0,"name":"古典文學","category_json_url":"http://172.16.242.14:8080/source/history/history.json"},{"category_id":1 ,"name":"流行音樂","category_json_url":"http://172.16.242.14:8080/source//popmusic/popmusic.json"}]}
#下面上碼:
def stripFile(oldFName,newFName): '''''remove the space or Tab or enter in a file,and output to a new file in the same folder''' fp = open(oldFName,"r+") newFp = open(newFName,"w") for eachline in fp.readlines(): newStr = eachline.replace(" ","").replace("\t","").strip() #print "Write:",newStr newFp.write(newStr) fp.close() newFp.close() if __name__ == "__main__": oldName = raw_input("input file name:") nameList = oldName.split(".") newName = "%s%s%s" % (nameList[0],"_new.",nameList[1]) stripFile(oldName,newName) print "finish output to new file:",newName
使用腳本時,如果腳本檔案和要處理的檔案在同一目錄下,則直接輸入檔案名,如果不在,則需要輸入檔案的完整路徑。
以上是如何截掉空格(包括tab)的詳細內容。更多資訊請關注PHP中文網其他相關文章!