Python Forum
pulling multiple lines from a txt
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
pulling multiple lines from a txt
#1
Howdy,

So basically the task is to pull rows from a text and do some math on them

I understand how to do the math part but I'm lost on how I can pull each row individually and have each int in the row as its own separate number? (the rows themselves are going to be entirely seperate throughout the process)

the rows look like this in the .txt file

40 65 77 80
32 62 96 22
Reply
#2
Try to post some code of what you tired next time.
Something like this.
lst = []
with open("number.txt") as f:
    for line in f:
        lst.append([int(i) for i in line.split()])
>>> lst
[[40, 65, 77, 80], [32, 62, 96, 22]]
>>> lst[0]
[40, 65, 77, 80]
>>> sum(lst[0])
262
Reply
#3
Hello,

I would have but again wasn't totally sure how to start. I have kind of headed in the right direction with the following script. however I'm unsure how i can loop it until the whole .txt is indexed and calculated as more lines can be added and removed to the .txt

path1 = input("File name: ")  # Asks for user input
f1 = open(path1)  # Opens the user specified file
lst = []
with f1 as file:
    for line in file:
        lst.append([int(i) for i in line.split()])
        lst1 = (sum(lst[0]) / len(lst[0]))
print(lst1)

f1.close()
Reply
#4
More like this,can add more lines and they will be calculated.
lst = []
with open("number.txt") as f:
    for line in f:
        lst.append([int(i) for i in line.split()])

avg = [sum(el) / len(el) for el in lst]
print(avg)
Output:
[65.5, 53.0]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Pulling Specifics Words/Numbers from String bigpapa 2 723 May-01-2023, 07:22 PM
Last Post: bigpapa
  Having trouble installing scikit-learn via VSC and pulling my hair out pythonturtle 1 721 Feb-07-2023, 02:23 AM
Last Post: Larz60+
  (Python) Pulling data from UA Google Analytics with more than 100k rows into csv. Stockers 0 1,172 Dec-19-2022, 11:11 PM
Last Post: Stockers
  Pulling username from Tuple pajd 21 3,226 Oct-07-2022, 01:33 PM
Last Post: pajd
  How to write the condition for deleting multiple lines? Lky 3 1,100 Jul-10-2022, 02:28 PM
Last Post: Lky
  Delete multiple lines from txt file Lky 6 2,204 Jul-10-2022, 12:09 PM
Last Post: jefsummers
  Display table field on multiple lines, 'wordwrap' 3python 0 1,747 Aug-06-2021, 08:17 PM
Last Post: 3python
  Pulling Information Out of Dictionary Griever 4 2,825 Aug-12-2020, 02:34 PM
Last Post: Griever
  Iterate 2 large text files across lines and replace lines in second file medatib531 13 5,707 Aug-10-2020, 11:01 PM
Last Post: medatib531
  print python json dump onto multiple lines lhailey 2 19,651 Mar-02-2020, 12:47 PM
Last Post: vishalhule

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020