Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reordering text file: Python

I have many text files. All of them have the following kind of structure.

textfile.txt

id|name|dataType
5|aa|String
4|bb|DateTime
|dd|DateTime
1|cc|DateTime
3|dd|DateTime

I would like to read all these text files one by one and reorder them based on their id and rows with no id should be excluded.
After that I would like to get the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

id|name|dataType
1|cc|DateTime
3|dd|DateTime
4|bb|DateTime
5|aa|String

Is there any pythonic way to do this?

>Solution :

You can use:

(pd.read_csv('textfile.txt', sep='|')
   .loc[lambda d: d['id'].notna()]
   .convert_dtypes()
   .sort_values(by='id')
   .to_csv('out.txt', sep='|', index=False)
)

out.txt:

id|name|dataType
1|cc|DateTime
3|dd|DateTime
4|bb|DateTime
5|aa|String
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading