python获取文件名并在另一个脚本中打开

标签 python file variables import

我有一个 one.py 为:

一个.py

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

我有另一个文件two.py,我需要从“one.py”打开“文件名”:

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

请帮我解决这个问题,它没有获取文件名。答案将不胜感激!

最佳答案

一个.py:

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

主.py:

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

在 Python 中,除非返回变量,否则无法访问函数中的变量。

编辑:

尝试

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

关于python获取文件名并在另一个脚本中打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25185286/

相关文章:

python - 我需要 Anaconda 32 位和 64 位

python - celery 任务中的grpc超时

c++ - ifstream 打不开

file - 动态 Gnuplot 图

php - 使用正则表达式在字符串中查找变量

python - 将重叠的间隔对象与依赖项合并

python - 使用随机函数(python)

c++ - 查找并替换文本文件中的字符串并输出到另一个文件

linux - bash:如何在 for 循环中访问 "dynamic declared variable"

Python 在函数调用中声明变量?