Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Read text and write into csv. Replace empty columns as a default 'N/A' value

Tags:

python

text

csv

I have a txt file, 'iteration.txt'. I only want to grab the data after 'Section' to be written into csv.
'Section A' has 2 inputs & outputs. 'Section B' has no inputs and outputs, I would like to put 'N/A' at empty columns.

'iteration.txt'

Input-> 000
Output-> 000
Codex153 @ Section_A_Iterating
Input-> 101
Output-> 010
unwanted data
Input-> 320
Output-> 321
unwanted data
Codex173 @ Section_B_Extracting
Codex183 @ Section_C_Iterating
unwanted data
unwanted data
Input->011
Output-> 011

Code I've done:

with open('iteration.csv', 'w') as writer:
    flag = False
    writer.write ('Section,Input,Output'+'\n')
    for eachline in open('iteration.txt').readlines():

        if 'Section' in eachline:
            flag = True
            writer.write (eachline.split()[-1]+'\n')
            #print (section_list)

        if flag:
            if 'Input' in eachline:
                writer.write (eachline.strip() + '\n')

            if 'Output' in eachline:
                writer.write(eachline.strip() + '\n')

Csv output from code above:

enter image description here

Expected csv data:

enter image description here

Sorry I'm new in this, I'm not too sure how do I put 'N/A' at empty columns, and how to place the data according to it's respective headers. Is there any simple way to do this, preferrably without changing the code above too much? Thanks!

like image 235
SirCuddles Avatar asked Aug 01 '26 12:08

SirCuddles


1 Answers

with the function .fillna('N/A') you can fill empty or non existing values.

like image 94
Passi Avatar answered Aug 03 '26 03:08

Passi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!