I currently have the below function within my code:-
def openFiles():
file1 = open('file1.txt', 'w')
file2 = open('file2.txt', 'w')
What I'm hoping to do is now, in a second method is to write to the open file. However, whenever I try to write to the files using for example "file1.write("hello")", an error is returned informing me that "global variable 'file1' is not defined"
. I've tried declaring 'file1' as a string at the beginning of my code but obviously, as it isn't a string but an object, I'm unsure how to write to it.
Any suggestions? I want a number of functions to have access to the files hence why I'd like a separate function that opens them.
Thanks
Edited to represent a Class
class TestClass:
def openFiles():
file1 = open('file1.txt', 'w')
file2 = open('file2.txt', 'w')
def write_to_files():
????????
Use open() with the "r+" token to open a file for both reading and writing. Call open(filename, mode) with mode as "r+" to open filename for both reading and writing. The file will write to where the pointer is.
The function call is made from the Main function to Function1, Now the state of the Main function is stored in Stack, and execution of the Main function is continued when the Function 1 returns.
The open() function opens a file, and returns it as a file object.
You can use python global keyword as shown below.
def openFiles():
global file1
global file2
file1 = open('file1.txt', 'w')
file2 = open('file2.txt', 'w')
def writeFiles():
file1.write("hello")
openFiles()
writeFiles()
However I would recommend you use a class for this instead. For example.
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")
You can then do:
>>> fileHandler = FileOperations()
>>> fileHandler.open_files()
>>> fileHandler.write_files()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With