Domanda

I am trying to add a value to a list from a file, and then be able to add the values from the file to the list. This is what I have:

L = []        
def readFile(L):
    ui = input("Please enter your file name:")
    r = open(ui, 'r')
    files = r.readlines()
    for line in files:
        return float(line)
    L.append(line)
    r.close()

def fileAddValue(L):
    ui = input("Please enter your file name:")
    val = float(input("Enter the value you would like to add to the list: "))
    r = open(ui, 'a')
    file = r.write(str(val) + '\n')
    for ix in r:
        x = float(ix)
    L.append(x)
    L.sort()
    r.close()
È stato utile?

Soluzione

You have a few problems...

First, when you open a file you need to use with, this will handle closing your file for you.

Now, when you read each line in turn you are returning the first one. That returns from the whole function so is not what you want. I take it you want to append each item onto your list.

Also, your functions are better made generic. Pass in the filename and the data. Get them outside the function for more flexibility.

It is not clear what you want to do here. I have assumed you want to specify values to add to a list which is persisted in a file. There are better ways to do this. This is my attempt based on your original code.

def readFile(ui):
    L = []
    with open(ui, 'r') as f:
        for line in f.readlines():
            L.append(float(line))
    return sorted(L)

def fileAddValue(ui, val):
    with open(ui, 'a') as f:
        f.write(str(val) + '\n')

ui = raw_input("Please enter your file name:")
L = readFile(ui)
print('original file:')
print(L)
val = float(raw_input("Enter the value you would like to add to the list: "))
fileAddValue(ui, val)
L = readFile(ui)
print('updated file:')
print(L)

Altri suggerimenti

Do you need something like that?

L = []
def readFile():
    ui = input("Please enter your file name:")
    r = open(ui, 'r')
    files = r.readlines()
    for line in files:
        value = float(line)
        L.append(value)
    r.close()

def fileAddValue():
    ui = input("Please enter your file name:")
    val = float(input("Enter the value you would like to add to the list: "))
    r = open(ui, 'a+')
    r.write(str(val) + '\n')
    for ix in r:
        x = float(ix)
        L.append(x)
    L.append(val)
    L.sort()
    r.close()

if __name__ == '__main__':
    readFile()
    fileAddValue()
    print(L)

While it's non-pytonic (tried to not touch your code unless necessary), it works if I got your question right. Indenting code is important in Python and returning from a function guarantees that code after return will never run. If you want a function that "returns" several values so you can iterate over that "function" with for, use yield instead of return.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top