Skip to content Skip to sidebar Skip to footer

Using Zip To Read A File Vertically And Search Through The Zipped List

I need to read a file containing information on different lines - for example the file may contain 12345678910 abcdefghij zyxwvutsrq I will then need to read the code vertically,

Solution 1:

This program prints the columns of its input file:

withopen('input.txt') as input_file:
    rows= input_file.readlines()
rows= zip(*[row.strip() forrowinrows])
rows= [''.join(row) forrowinrows]
print rows

Result, when using OP's data:

['1az', '2by', '3cx', '4dw', '5ev', '6fu', '7gt', '8hs', '9ir', '1jq']

Solution 2:

You don't need to call readlines or make any intermediary lists, you just need to transpose the file object, using map to remove the newlines:

withopen("test.txt") as f:
    # python2 itertools.izip, itertools.imap print(["".join(r) for r inzip(*map(str.rstrip,f))])

Output:

['1az', '2by', '3cx', '4dw', '5ev', '6fu', '7gt', '8hs', '9ir', '1jq']

Post a Comment for "Using Zip To Read A File Vertically And Search Through The Zipped List"