Tamamo
Tamamo

Reputation: 93

Getting specific element(s) from after read from file

After I read from file:

with open(fileName) as f:
    for line in f:
        print(line.split(","))     #split the file into multiple lists

How do I get some specific element(s) from those lists?

For example, only elements with index[0 to 3], but discard/ignore any elements after that.

Upvotes: 0

Views: 31

Answers (2)

Rory Daulton
Rory Daulton

Reputation: 22544

If you want to save the first three items in each line, you could use a list comprehension

with open(fileName) as f:
    firstitems = [line.rstrip().split(",")[0:3] for line in f]

Note that the rstrip() is needed to remove the final newline character, if there are fewer than four items in a line. Note that the "items" are all strings, even if they look like other types. If you want integers, for example, you will need to convert them to integers.

Then you can print them:

for line in firstitems:
    print(line)

Upvotes: 1

U13-Forward
U13-Forward

Reputation: 71580

Try the below code:

with open('f.txt') as f:
    print('\n'.join([i for i in f.read().split(',')[0:3]]))

Upvotes: 1

Related Questions