How to get data out of a def function in python

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

提交回复
热议问题