Question

My program crashes on the line (print('\nThe maximum value from the file is {}'.format(max(i)))) with the...

My program crashes on the line (print('\nThe maximum value from the file is {}'.format(max(i)))) with the error message TypeError: "int" object not iterable. The purpose of this program is to create an process binary files. Can you tell me what's going wrong?

Thanks!

( *'s indicate indentation)

from sys import argv
from pickle import dump
from random import randint
from pickle import load

if (argv[1] == 'c'):

****output_file = open(argv[2], 'wb')
****for i in range(int(argv[3])):
********dump(randint(int(argv[4]), int(argv[5])), output_file)
****output_file.close()

****print('{} random integer values have been written to the file {}.'
****.format(argv[3], argv[2]))
****print('Program now terminating.')
****input('Press Enter to continue ... ')
****print()

elif (argv[1] == 'p'):
****num_spaces = 1
****input_file = open(argv[2], 'rb')

****while True:
******try:
********i = load(input_file)
********print('\nThe maximum value from the file is {}'.format(max(i)))    #This is where the error occurs
********print('The minimum value from the file is {}'.format(min(i)))
********print('The sum of the values from the file is {}'.format(sum(i)))
********print('The average of the values from the file is'
********' %.2f' % (sum(i) / len(i)))
********print("Here are the integers from integers.dat:")
********print()
********print('And here are all the values from the file, sorted ascending'
********',\n with a maximum of 10 per line, and with each value in'
********' {} spaces:'.format(num_spaces))

********print(i, end=' ')

****except EOFError:
******input_file.close()
******break
****print('\nProgram now terminating.')
****input("Press Enter to continue ... ")
****print()

Also all instructions are given from the cmd prompt.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

$ python x.py c input 10 4 40 10 random integer values have been written to the file input. Program now terminating. Press En

from sys import argv
from pickle import dump
from random import randint
from pickle import load

if (argv[1] == 'c'):

    output_file = open(argv[2], 'wb')
    data = []
    for i in range(int(argv[3])):
        data.append(randint(int(argv[4]), int(argv[5])))
    dump(data, output_file)
    output_file.close()

    print('{} random integer values have been written to the file {}.'.format(argv[3], argv[2]))
    print('Program now terminating.')
    input('Press Enter to continue ... ')
    print()

elif (argv[1] == 'p'):
    num_spaces = 1
    input_file = open(argv[2], 'rb')

    while True:
        try:
            i = load(input_file)
            print('\nThe maximum value from the file is {}'.format(max(i)))    #This is where the error occurs
            print('The minimum value from the file is {}'.format(min(i)))
            print('The sum of the values from the file is {}'.format(sum(i)))
            print('The average of the values from the file is' ' %.2f' % (sum(i) / len(i)))
            print("Here are the integers from integers.dat:")
            print()
            print('And here are all the values from the file, sorted ascending\n with a maximum of 10 per line, and with each value in {} spaces:'.format(num_spaces))

            print(i, end=' ')

        except EOFError:
            input_file.close()
            break
        
    print('\nProgram now terminating.')
    input("Press Enter to continue ... ")
    print()

**************************************************
I have corrected the code.. You were doing multiple dumps. you should dump the whole list. If you dump only a number at a time, then you are reading only a integer in loads method. Hence max(integer) gives you error, because max works on list, not on integers.

Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.

Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.

Add a comment
Know the answer?
Add Answer to:
My program crashes on the line (print('\nThe maximum value from the file is {}'.format(max(i)))) with the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • how do I write this code without the imports? I don't know what pickle is or...

    how do I write this code without the imports? I don't know what pickle is or os.path import pickle # to save and load history (as binary objects) import os.path #to check if file exists # character value mapping values = {'A': 1, 'B': 3, 'C': 3, 'D': 2, 'E': 1, 'F': 4, 'G': 2, 'H': 4, 'I': 1, 'J': 8, 'K': 5, 'L': 1, 'M': 3, 'N': 1, 'O': 1, 'P': 3, 'Q': 10, 'R': 1, ' S': 1,...

  • I have this program that works but not for the correct input file. I need the...

    I have this program that works but not for the correct input file. I need the program to detect the commas Input looks like: first_name,last_name,grade1,grade2,grade3,grade4,grade5 Dylan,Kelly,97,99,95,88,94 Tom,Brady,100,90,54,91,77 Adam,Sandler,90,87,78,66,55 Michael,Jordan,80,95,100,89,79 Elon,Musk,80,58,76,100,95 output needs to look like: Tom Brady -------------------------- Assignment 1: A Assignment 2: A Assignment 3: E Assignment 4: A Assignment 5: C Final Grade: 82.4 = B The current program: import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class main {    public static void main(String[]...

  • Problem: Write a program that behaves as described below.If the first command-line argument after the program...

    Problem: Write a program that behaves as described below.If the first command-line argument after the program name (argv[1]) is “--help”, print the usage information for the program. If that argument is not “--help”, you are to expectargv[1]and subsequent arguments to be real numbers(C, integer, float, or double types)in formats acceptable to the sscanf()function of the C library or strings of ASCII chars that are not readable as real numbers. You are to read the numbers, count them and calculate the...

  • Finish the given ProcessFile.java program that prompts the user for a filename and reprompts if file...

    Finish the given ProcessFile.java program that prompts the user for a filename and reprompts if file doesn’t exist. You will process through the file skipping any text or real (double) numbers. You will print the max, min, sum, count, and average of the integers in the file. You will want to create test files that contain integers, doubles, and Strings. HINT: Use hasNextInt() method and while loop. You may also want to use Integer.MAX_VALUE and Integer.MIN_VALUE for the initialization of...

  • I am having trouble with my Python code in this dictionary and pickle program. Here is...

    I am having trouble with my Python code in this dictionary and pickle program. Here is my code but it is not running as i am receiving synthax error on the second line. class Student: def__init__(self,id,name,midterm,final): self.id=id self.name=name self.midterm=midterm self.final=final def calculate_grade(self): self.avg=(self.midterm+self.final)/2 if self.avg>=60 and self.avg<=80: self.g='A' elif self.avg>80 and self.avg<=100: self.g='A+' elif self.avg<60 and self.avg>=40: self.g='B' else: self.g='C' def getdata(self): return self.id,self.name.self.midterm,self.final,self.g CIT101 = {} CIT101["123"] = Student("123", "smith, john", 78, 86) CIT101["124"] = Student("124", "tom, alter", 50,...

  • HELP! HOW WOULD I WRITE THIS IN PSEUDOCODE? from itertools import accumulate from collections import Counter...

    HELP! HOW WOULD I WRITE THIS IN PSEUDOCODE? from itertools import accumulate from collections import Counter def addvalues(a, b): if type(a) is str: a = a.strip("\n") if type(b) is str: b = b.strip("\n") return int(a) + int(b) def maxValues(a, b): if type(a) is str: a = a.strip("\n") if type(b) is str: b = b.strip("\n") a = int(a) b = int(b) return max(a, b) def main(): counter = 0 total = 0 maximum_cars = 0 file = open("MainAndState.dat", "r") maximum =...

  • Keep getting an Error in my fortran program in which I find the maximum value of...

    Keep getting an Error in my fortran program in which I find the maximum value of the inputted integers. MY CODE: PRINT *, "The Max Entered Element is" PRINT *, MAX (a(i), i = 1, n) ERROR: PRINT *, MAX (a(i), i = 1, n) 1 Error: Missing keyword name in actual argument list at (1)

  • I am given an input file, P1input.txt and I have to write code to find the...

    I am given an input file, P1input.txt and I have to write code to find the min and max, as well as prime and perfect numbers from the input file. P1input.txt contains a hundred integers. Why doesn't my code compile properly to show me all the numbers? It just stops and displays usage: C:\> java Project1 P1input.txt 1 30 import java.io.*; // BufferedReader import java.util.*; // Scanner to read from a text file public class Project1 {    public static...

  • //please help I can’t figure out how to print and can’t get the random numbers to...

    //please help I can’t figure out how to print and can’t get the random numbers to print. Please help, I have the prompt attached. Thanks import java.util.*; public class Test { /** Main method */ public static void main(String[] args) { double[][] matrix = getMatrix(); // Display the sum of each column for (int col = 0; col < matrix[0].length; col++) { System.out.println( "Sum " + col + " is " + sumColumn(matrix, col)); } } /** getMatrix initializes an...

  • Java programming How do i change this program to scan data from file and find the...

    Java programming How do i change this program to scan data from file and find the sum of the valid entry and count vaild and invalid entries The provided data file contains entries in the form ABCDE BB That is - a value ABCDE, followed by the base BB. Process this file, convert each to decimal (base 10) and determine the sum of the decimal (base 10) values. Reject any entry that is invalid. Report the sum of the values...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT