Singh2013
Singh2013

Reputation: 179

Python Reading file error with array

My File:

Offices 10
MedicalOffice 15
PostOffice 30
Mall 200

How do I make the python to read only the second column. Like get:

10
15
30
200

I have tried possibly ways to make it only read, 10, 15, 30, etc... Instead of the names. I tried this without the names, it works fine. But I need to include the names in the textfile. Any help? Thanks

def something(file1):
    with file1 as f:
        nums = [int(line) for line in f]
        print("Read from File: ", nums)


textFileName = input("Enter the filename: ")
file1 = open(textFileName)
something(file1)

Thank you.

Upvotes: 0

Views: 51

Answers (3)

SheetJS
SheetJS

Reputation: 22925

To read the second column, split the lines and take the second field:

[x.split()[1] for x in open(textFileName,"r")]

If you want numbers, just call int:

[int(x.split()[1]) for x in open(textFileName,"r")]

Upvotes: 3

Josha Inglis
Josha Inglis

Reputation: 1048

Similar to @Nirk's answer, but with improved file handling:

with open('/path/to/file.txt', 'r') as f:
    nums = [x.strip().split()[-1] for x in f]

Upvotes: 1

abarnert
abarnert

Reputation: 366133

You can't only read the second column.

But you can read both columns, ignore the first column, and only use the second.

For example:

def something(file1):
    with file1 as f:
        lines = (line.partition(' ') for line in f)
        nums = [int(line[-1]) for line in lines)
        print("Read from File: ", nums)

I did this in two steps, just to make it easier to see the part that's new (the partition) vs. the part you already had (the int). You can cram it all together into a single listcomp if you prefer:

        nums = [int(line.partition(' ')[-1]) for line in f]

Anyway, partition splits each line at the first space, so you get, e.g., ('Offices', ' ', '10'). The [-1] takes the last part, the '10'. And then there's the int, which you already know about.

Upvotes: 2

Related Questions