简体   繁体   中英

How do I initialise a Python file_object without opening a file

I need to declare a file_object globally and much later, open a file and in so doing store a value to it.

To explain: Python allows me to declare a string variable outside of any class or function by simply declaring:

stringName = str()

and then much later assigning a value EG:

stringName = 'this is a string'

I need to do much the same with a file_object to which I can much later assign a value EG:

fileObject = ????????

and later

fileObject = open('fileName', mode, bufsize)

How do I get this past Python's syntax filters?

You can define the variable as None and then use it in your local function via global :

file = None

def func():
    global file
    file = open(fname, 'w+')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM