Home > OS >  Replacing values in a file with user input values if above a certain number
Replacing values in a file with user input values if above a certain number

Time:02-01

I am working on a homework assignment for introductory Python, so I don't want an outright answer, just clarification. My question states to implement a function to ask the user for a list of numbers, then to check if the number is greater than another value and if so, to write those values to a file. I believe what I have written is correct but I am unsure how to check it. Below is the code I have written:

def numberLogger (filename,minval):
    'ask the user to enter a list of numbers.  If a number is greater than or equal to the second paramter, append it to a file'
    userdata=input('Enter a series of numbers seperated by a comma: ')
    u=userdata.split(',')
    for i in u:
        i=int(i)
        if i>=minval:
            infile=open(filename,'w')
            infile.write(i)
            infile.close()

Any help is much appreciated, as I said, it is homework so please don't just give away the answer, rather guide me to it.

CodePudding user response:

To clean this up, I would do a few things. Only open the file once.

def numberLogger(filename, minval):
    userdata = input('Enter a series of numbers seperated by a comma: ')
    u = userdata.split(',')
    with open(filename, 'w') as infile:
        for i in u:
            i=int(i)
            if i>=minval:
                infile.write(i)

You can also use a generator expression to filter out your data.

def numberLogger(filename, minval):
    userdata = input('Enter a series of numbers seperated by a comma: ')
    u = userdata.split(',')
    with open(filename, 'w') as infile:
        for i in (i for x in u for i in [int(x)] if i >= minval):
            infile.write(i)
  •  Tags:  
  • Related