How to cut off spaces (including tabs)

anonymity
Release: 2019-05-25 11:02:12
Original
2379 people have browsed it

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"
      }
        ]
}
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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 [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!