Home >Backend Development >Python Tutorial >python去除文件中空格、Tab及回车的方法

python去除文件中空格、Tab及回车的方法

WBOY
WBOYOriginal
2016-06-10 15:05:171471browse

本文实例讲述了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

使用脚本时,如果脚本文件和要处理的文件在同一目录下,则直接输入文件名,如果不在,需要输入文件的完整路径。

记得听Cliff说过,程序员就要有一个批量处理的意识,要学会发挥机器的力量,感觉还是很对的。

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn