This article describes how to remove spaces, tabs, and carriage returns from a python file. It involves Python related techniques for file and string operations, for more information about how to remove spaces, tabs, and carriage return in python, see the following example. We will share this with you for your reference. The details are as follows:
In recent development work, in order to cope with the competition schedule, the json files on the server are manually written. After writing, it is found that the formats are very regular and easy to read, however, client requests do not need any useless characters such as spaces, tabs, and carriage returns added in json for the purpose of format. Then, a script is written in python to remove spaces, carriage returns, and line breaks in the file.
Original json file:
{"Amount": "2", "content": [{"category_id": 0, "name": "classical literature", "category_json_url": "http: // 172.16.242.14: 8080/source/history. json "},{" category_id ": 1," name ":" pop music "," category_json_url ":" http: // 172.16.242.14: 8080/source // popmusic/popmusic. json "}]}
Files processed by scripts:
The Code is as follows:
{"Amount": "2", "content": [{"category_id": 0, "name": "classical literature", "category_json_url": "http: // 172.16.242.14: 8080/source/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, enter the file name directly. If not, enter the complete path of the file.
I remember Cliff said that programmers should have a sense of batch processing. It is still right to learn to exert the power of machines.