Python to merge rows


#1

Transpose using python

@jagking I was looking into this code and was trying to refine it further,
1.) if the length of line is less than 50 , (suppose the length of line is 45) it should insert 5 blank spaces to streamline the data, i was trying it with all possible cases but it is not appending the blank spaces to the last line when only single line is there for ex:
abc…
abc…
abc…

2.) in case xyz occurs, it should skp the line.

I was expecting that it should append blank spaces to make each row of length 50:
for example:
abc 123 456 #if row is less than 50 , it should append blank spaces to sync with all other rows



def format_file(inFile, outFile,dic):
    expected = 0
    gap = " "*50
    len1=50
    newLine = []
    join = " ".join
    write = outFile.write

    for line in inFile:
        sLine = line[:-1]
        linePos = dic[line[:3]]
        if linePos == 4:
            continue
        if linePos == 0:  
            if newLine:
                if len(line)!=len1:
                    gap2=len1-len(line)
                newline.append(" "*gap2)
                write(join(newLine)+"\n")
                newline = [sLine]
            newLine = [sLine]
            expected = 1
        else:
            gaps = linePos - expected
            if gaps != 0:
                newLine.append(gap*gaps)
                expected = linePos + 1
            else:
                expected += 1
            newLine.append(sLine)
            if len(line)!=len1:
                gap2=len1-len(line)
            newline.append(" "*gap2)

    if newLine:
        newLine[-1] = line
        if len(line)!=len1:
            gap2=len1-len(line)
        newline.append(" "*gap2)

        write(join(newLine))
            
def main():
    positions = {"abc":0,
                 "cde":1,
                 "efg":2,
                 "hij":3,
                 "xyz":4}
    with open("Text.txt","r") as inTxt, open("NewText.txt","w")as outTxt:
        format_file(inTxt,outTxt,positions)
        
if __name__ == "__main__":
    main() 



#2

If you want to have the line as a minimum of 50 characters long, use string formatting. E.g. “{: <50}”.format(sLine). It goes :[character to use to fill in the deficit][direction to push the text][minimum length of the string]. So we use [space][left arrow so spaces are added to the end of the string][50 characters minimum].

Don’t have continue for xyz. Instead put “\n” or chr(10) to denote a new line. Continue just moves onto the next item on the for loop without doing anything else after the continue statement.
EDIT: Miss read it, I think you mean if xyz occurs you want it to discard the whole line. Right? You will need to reset newLine to an empty list before continue if that is the case…


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.