-2

I have a txt File and on every line is a number (Line 1 = 1, Line 2 = 2 etc.). The file I want to read in Python

I want to add up line 1 and 3 in python (1+3). How can I do this?

I tried:

    file = open(“example.txt”,”r”) 

    line1 = file.read('line 1') 
    line3 = file.read('line 3')

    file.close() 


result = line1 + line3
claudio26
  • 149
  • 1
  • 1
  • 8
  • 2
    what have you tried? Please read: https://stackoverflow.com/help/how-to-ask for what is a good question – asosnovsky Dec 29 '17 at 15:57
  • 1
    It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the [FAQ] and [ask]. – MooingRawr Dec 29 '17 at 15:58
  • 2
    Do 1 + 3? What exactly is the problem? – Mad Physicist Dec 29 '17 at 15:58
  • Sorry for the bad description. I added the code. I dont know how i can only read in the line 1 and line 3... – claudio26 Dec 29 '17 at 16:02
  • Possible duplicate of [Reading specific lines only (Python)](https://stackoverflow.com/questions/2081836/reading-specific-lines-only-python) – Tai Dec 29 '17 at 16:21

1 Answers1

0

One way is to use readlines. This question has been answered in Reading specific lines only (Python) Try to do some search next time:P

with open(“example.txt”,”r”) as f:
    lines = f.readlines() # this will gets all the lines at once
    line1 = lines[0]      # get the first line 
    line3 = lines[2]      # get the third line
    result_int = int(line1) + int(line3) # if you are doing integer addtion. -> 3
    result_str = line1 + line3 # will give you: 13

In many programming languages, the index starts at 0 rather than 1. This is why we are fetching it using indexes 0 and 2.

Tai
  • 7,684
  • 3
  • 29
  • 49