kingpenguin
January 5th, 2017, 11:02 PM
Ok at the moment I have a python 3 program. What I am trying to do is have a file open in the main block of code and have a function that will be able to write to this file. something like this
f = open('test.txt', 'a')
def write(word):
f.write(word)
Dont get me wrong I know this will not work as is but it seems really dumb to keep opening a file over and over after every time the function is called. Because what i have at the moment is
def write(word):
with open('test.txt', 'a') as f:
f.write(word)
but this function will be called a bunch and the 2nd way seems really bad for efficiency
f = open('test.txt', 'a')
def write(word):
f.write(word)
Dont get me wrong I know this will not work as is but it seems really dumb to keep opening a file over and over after every time the function is called. Because what i have at the moment is
def write(word):
with open('test.txt', 'a') as f:
f.write(word)
but this function will be called a bunch and the 2nd way seems really bad for efficiency