Python Forum
reading txt file putting in list function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
reading txt file putting in list function
#8
(Jul-17-2019, 02:41 PM)perfringo Wrote: I observe that this is second thread on same topic.

There is no information about file format available but my random guess is:

with open(“nums.txt”, “r”) as f:
    numbers = [int(num) for num in f.read().split()]

Sry changed the question from the other, ill be moving back to that topic soon about the IOERRORS.

(Jul-17-2019, 02:54 PM)ichabod801 Wrote: Okay, then you just need to split by lines. The code perfringo posted is one way to do that. Another way, is to just loop over the file:

with open('nums.txt') as nums_file:
    numbers = []
    for line in nums_file:
        numbers.append(int(line))
Or you can do a list comprehension like perfringo did.
Works perfectly

with open('nums.txt') as nums_file:
    numbers = []
    for line in nums_file:
        numbers.append(int(line))
print("Total =", sum(numbers))
def Average(numbers):
    return sum(numbers) / len (numbers)
print("Average =", round(Average(numbers), 2))
Reply


Messages In This Thread
RE: reading txt file putting in list function - by Expel - Jul-17-2019, 03:18 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Reading an ASCII text file and parsing data... oradba4u 2 1,390 Jun-08-2024, 12:41 AM
Last Post: oradba4u
Sad problems with reading csv file. MassiJames 3 2,500 Nov-16-2023, 03:41 PM
Last Post: snippsat
  trouble reading string/module from excel as a list popular_dog 0 893 Oct-04-2023, 01:07 PM
Last Post: popular_dog
  Reading a file name fron a folder on my desktop Fiona 4 2,049 Aug-23-2023, 11:11 AM
Last Post: Axel_Erfurt
  Reading data from excel file –> process it >>then write to another excel output file Jennifer_Jone 0 2,076 Mar-14-2023, 07:59 PM
Last Post: Jennifer_Jone
  function return boolean based on GPIO pin reading caslor 2 2,048 Feb-04-2023, 12:30 PM
Last Post: caslor
  Reading a file JonWayn 3 1,933 Dec-30-2022, 10:18 AM
Last Post: ibreeden
  Reading Specific Rows In a CSV File finndude 3 1,794 Dec-13-2022, 03:19 PM
Last Post: finndude
  Excel file reading problem max70990 1 1,639 Dec-11-2022, 07:00 PM
Last Post: deanhystad
  Replace columns indexes reading a XSLX file Larry1888 2 1,692 Nov-18-2022, 10:16 PM
Last Post: Pedroski55

Forum Jump:

User Panel Messages

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