Writing to a file is open in the second function (Python)

I currently have the following function inside my code: -

def openFiles():
    file1 = open('file1.txt', 'w')
    file2 = open('file2.txt', 'w')

What I hope to do now in the second method is to write to an open file. However, whenever I try to write files, for example, "file1.write (" hello "), an error message is returned "global variable 'file1' is not defined". I tried to declare "file1" as a line at the beginning of my code, but obviously, since this is not a line, but an object, I am not sure how to write to it.

Any suggestions? I want some functions to have access to files, so I need a separate function that opens them.

thank

Edited to represent the class

class TestClass:
    def openFiles():
        file1 = open('file1.txt', 'w')
        file2 = open('file2.txt', 'w')

    def write_to_files():
        ????????
+5
source share
1

python global, .

def openFiles():
    global file1
    global file2
    file1 = open('file1.txt', 'w')
    file2 = open('file2.txt', 'w')

def writeFiles():
    file1.write("hello")

openFiles()
writeFiles()

. .

class FileOperations:
    def open_files(self):
        self.file1 = open('file1.txt', 'w')
        self.file2 = open('file2.txt', 'w')

    def write_to_files(self):
        self.file1.write("hello")

:

>>> fileHandler = FileOperations()
>>> fileHandler.open_files()
>>> fileHandler.write_files()
+9

All Articles