Reputation:
My initial data was this but i want to write this data such that it is formatted in "cat_id|content" like the one below this
5 Name NRIC DOB 1932.11.26 Race Chinese Sex Female ND - PATIENT CARE RECORD
4 Name NRIC DOB 1933.05.01 Race Chinese Sex Male PM - PATIENT CARE RECORD
I would like the desired format to be write in this format in text file:
cat_id|content
5|Name NRIC DOB 1932.11.26 Race Chinese Sex Female ND - PATIENT CARE RECORD
4|Name NRIC DOB 1933.05.01 Race Chinese Sex Male PM - PATIENT CARE RECORD
i did this because large number of content in a forloop (just for your understanding)
text_file = open("ED_Notes.txt", 'w')
for item in arr_cat:
text_file.write("%s\n" % item)
please do help thanks!! :)
Upvotes: 0
Views: 70
Reputation: 82765
This should help.
Demo:
with open(filename) as infile:
toWrite = ["|".join(line.split(" ", 1)) for line in infile] #Iterate each line and split by first space and the join by |
with open(filename, "w") as outfile: #Write back to file.
for line in toWrite:
outfile.write(line)
Output:
5|Name NRIC DOB 1932.11.26 Race Chinese Sex Female ND - PATIENT CARE RECORD
4|Name NRIC DOB 1933.05.01 Race Chinese Sex Male PM - PATIENT CARE RECORD
Upvotes: 1
Reputation: 85
I think you could do this with regular expressions.
I would try something like this:
import re
text_file = open("ED_Notes.txt", 'w')
for item in arr_cat:
m = re.search("([0-9]) ([a-zA-Z].*)",item)
text_file.write(m.group(1)+"|"+m.group(2))
text_file.close()
I'm sorry I'm in hurry so I didn't test it
Upvotes: 0