简体   繁体   中英

How do I write a text file with certain format?

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!! :)

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 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM