python to get file name and open in another script

2019-08-08 20:29发布

问题:

I have a one.py as:

one.py

def file_save():
    f = th1.asksaveasfile(mode='w', defaultextension=".txt")
    filename = f.name

I have another file two.py where i need to open 'filename' from 'one.py':

from one import filename
with open(filename,'w'):
     print('hello')

please help me to fix the problem,its not getting filename.Answers will be appreciated!

回答1:

One.py:

def file_save():
    f = th1.asksaveasfile(mode='w', defaultextension=".txt")
    filename = f.name
    return filename;

Main.py:

from one import file_save
with open(file_save,'w'):
   print('hello')

In Python, you cannot access a variable in a function unless it is returned.

Edit:

Try

f = open(file_save, 'w')
print('hello')