1

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, so my list would be:

(1az)(2by)

The code I have so far is

# grid is the original file that has been read and put into a list
grid2 = zip(*grid) 
for word in words :
        for charc in grid2 :
            if word in charc :
                wordsFound.append(word )

I then run then the zip(*grid) through my search function but it just returns the entire words file and not just the words it has found

Any help will be appreciated, thank you.

T.Lowe
  • 15
  • 4

2 Answers2

0

This program prints the columns of its input file:

with open('input.txt') as input_file:
    rows = input_file.readlines()
rows = zip(*[row.strip() for row in rows])
rows = [''.join(row) for row in rows]
print rows

Result, when using OP's data:

['1az', '2by', '3cx', '4dw', '5ev', '6fu', '7gt', '8hs', '9ir', '1jq']
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
0

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:

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

Output:

['1az', '2by', '3cx', '4dw', '5ev', '6fu', '7gt', '8hs', '9ir', '1jq']
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321