Home  >  Article  >  Backend Development  >  How to cut off spaces (including tabs)

How to cut off spaces (including tabs)

anonymity
anonymityOriginal
2019-05-25 11:02:122560browse

The example of this article describes the method of removing spaces, tabs and carriage returns in files in python. The details are as follows:

The json files on the server are all written manually. After writing, I found that the format is very regular and easy to read. However, the client request does not require those added to the json for the sake of format. There are useless characters such as spaces, tabs, carriage returns, etc., so I used python to write a script to remove spaces, carriage returns, and line feeds from the file.

How to cut off spaces (including tabs)

Original json file:

{
  "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"
      }
        ]
}

File processed by script:

{"amount":"2","content ":[{"category_id":0,"name":"Classical Literature","category_json_url":"http://172.16.242.14:8080/source/history/history.json"},{"category_id":1 ,"name":"Pop Music","category_json_url":"http://172.16.242.14:8080/source//popmusic/popmusic.json"}]}

The code below:

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

When using a script, if the script file and the file to be processed are in the same directory, directly enter the file name. If not, you need to enter the full path of the file.

The above is the detailed content of How to cut off spaces (including tabs). For more information, please follow other related articles on the PHP Chinese website!

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