Python Forum
Read text file, process data and print specific output
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Read text file, process data and print specific output
#1
Please someone HELP!!!!
I have the below homework and no code I've tried worked so far!!!!!
_________________________________________________________________________________________________________
Write a Python script that will read a text file whose lines contain numbers separated by white-space; as output, the program will produce for each line of the original text file another line that will contain two numbers: the first will be the total number of entries in the line, and the second will be the sum of the numbers in the line.
Example:
Input file (test1.txt) contents:
1 3 5 12 0
2 3
1
-1 1
Expected Output:
Enter text file name: test1.txt
Output:
5 21
2 5
1 1
2 0
Reply
#2
What have you tried? (Post it in code tags.)
Reply
#3
And in addition to micseydel's advice - use meaningful and descriptive thread titles. I edited yours this time.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#4
Use .split() to split on the space (look it up). Convert to a list of numbers. Use len(the list) for your count. Loop and add to get the sum. Do this for each line in the file.
You are having trouble getting started but the loop can be done through a "list comprehension". Once you have solved it look that up to see how your loop could be condensed to a single line.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Exclamation URGENT: How to plot data from text file. Trying to recreate plots from MATLAB JamieAl 4 3,542 Dec-03-2023, 06:56 AM
Last Post: Pedroski55
  dictionary output to text file (beginner) Delg_Dankil 2 1,175 Jul-12-2023, 11:45 AM
Last Post: deanhystad
  Output File ? Kessie1971 11 1,974 May-11-2023, 08:31 AM
Last Post: buran
  Print not appearing in output dgizzly 1 1,204 Oct-14-2022, 09:55 PM
Last Post: rob101
  Using regex to count specific character in file shamishd 1 1,618 Oct-01-2021, 07:33 AM
Last Post: snippsat
  Reading a text until matched string and print it as a single line cananb 1 2,020 Nov-29-2020, 01:38 PM
Last Post: DPaul
  computer science coursework, read the text please and tell me if theres any specifics sixcray 4 2,611 Nov-11-2020, 03:17 PM
Last Post: buran
  Can we store value in file if we open file in read mode? prasanthbab1234 3 2,561 Sep-26-2020, 12:10 PM
Last Post: ibreeden
  Working with text data APK 4 2,488 Aug-22-2020, 04:48 AM
Last Post: buran
  [split] how to read a specific row in CSV file ? laxmipython 2 8,868 May-22-2020, 12:19 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

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