如何编写具有特定格式的文本文件?

时间:2018-09-26 09:54:17

标签: python format text-files

我的初始数据是这个,但我想写入此数据,以便将其格式化为 像这样的“ cat_id | content”

UISearchBar

我希望以这种格式在文本文件中写入所需的格式:

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 

之所以这样做,是因为forloop中有大量内容(仅供您理解)

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 

请帮忙谢谢!! :)

2 个答案:

答案 0 :(得分:1)

这应该有帮助。

演示:

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)

输出:

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 

答案 1 :(得分:0)

我认为您可以使用正则表达式来做到这一点。

我会尝试这样的事情:

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()

对不起,我很着急,所以我没有测试