How to get data out of a def function in python

后端 未结 3 766
北恋
北恋 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)
    

提交回复
热议问题