pulling multiple lines from a txt - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: pulling multiple lines from a txt (/thread-33446.html) |
pulling multiple lines from a txt - IceJJFish69 - Apr-26-2021 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 RE: pulling multiple lines from a txt - snippsat - Apr-26-2021 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 RE: pulling multiple lines from a txt - IceJJFish69 - Apr-26-2021 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() RE: pulling multiple lines from a txt - snippsat - Apr-26-2021 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)
|