How to get data out of a def function in python

后端 未结 3 758
北恋
北恋 2020-12-12 06:43

Trying to simplify lots of repetitive reading and writing in a script of mine, and I can not figure out how to get data out of def readfile.

def          


        
相关标签:
3条回答
  • 2020-12-12 07:12
    • In Python, variables from inside a function are generally not accessible from the outside (Look up variable scoping).
    • You can put a return statement at the end of a function to return variables (readvar in this case) (and you almost always should).
    • Then you can assign the returned argument (readvar) to a new variable (e.g. rv).
    • You can also give it the same name.
    • Other Resources:
      • Python Scopes and Namespaces
      • Real Python: Defining Your Own Python Function
    def writefile(FILE, DATA):
        file = open(FILE, "w")
        X = str(DATA) 
        file.write(X)
        file.close()
        
        
    def readfile(FILE):
        file = open(FILE, "r")
        readvar = file.read()
        file.close()
        return readvar
    
    
    rv = readfile("BAL.txt")
    print(rv)
    
    0 讨论(0)
  • 2020-12-12 07:23

    You're unable to see the value of readvar because it's only locally defined within the scope of the readfile function, not globally, as you're attempting to use it when calling print(readvar).

    If you need a value to persist outside the scope of the function, you must return it to where the function is called, like so:

    def readfile(FILE):
        file = open(FILE, "r")
        file_data = file.read()
        file.close()
        return file_data
    
    file_data = readfile("my_file.txt")
    print(file_data)
    

    I'd also suggest using a with block when performing file operations. It's best practice as to ensure the file handle is correctly closed, even if exceptions occur. This improves the handling of any errors the operation may encounter. For example:

    def writefile(FILE, DATA):
        data = str(DATA) 
    
        with open(FILE, 'w') as write_stream:
            write_stream.write(data)
    
    def readfile(FILE):
        with open(FILE, 'r') as read_stream:
            file_data = read_stream.read()
    
        return file_data
    
    file_data = readfile("my_file.txt")
    print(file_data)
    

    If you wanted to access the file line-by-line, we simply include a for loop within the scope of with. For example, printing each line of the file:

    def readfile(FILE):
        with open(FILE, 'r') as read_stream:
            for line in read_stream
                print(line)
    
    0 讨论(0)
  • 2020-12-12 07:23

    simple. try this one

    def personal_data():

    name1 = input("What is you 1st Name?").upper()
    name2 = input("What is your last Name?").upper()
    return name1 + name2
    

    fname = personal_data()

    print(fname)

    0 讨论(0)
提交回复
热议问题