Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write to File open in Second Function (Python)

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():
        ????????
like image 838
thefragileomen Avatar asked Oct 29 '11 17:10

thefragileomen


People also ask

Can I open a file in both read and write mode Python?

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.

How do I use one function data to another function in Python?

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.

What is open () function in Python?

The open() function opens a file, and returns it as a file object.


1 Answers

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()
like image 160
solartic Avatar answered Oct 12 '22 19:10

solartic