You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python 3中将函数写入新文件?

How to Write a Python Function to a New File

Hey there! Let's sort out your problem. The issue with your current code is that you're trying to write the function object directly to the file—this will just output something like <function fun_one at 0x7f9b1c0b3d30> instead of the actual source code of your function. Here's how to fix it properly:

The inspect module lets you retrieve the source code of functions you've already defined. This is super handy if your function is complex or defined elsewhere in your codebase.

import inspect

def fun_one(x):
    print(x)

# Use 'w' mode to overwrite the file (use 'a' if you want to append instead)
# Using a `with` statement ensures the file is closed automatically
with open('file.py', 'w') as file_handler:
    # Get the source code of the function and write it to the file
    file_handler.write(inspect.getsource(fun_one))

Key Notes:

  • The with statement is preferred over manually calling close() because it handles file closure even if an error occurs.
  • inspect.getsource() works for functions defined in .py files, but might fail if the function was created in an interactive shell (like IPython or the default Python REPL).

Method 2: Write the Function as a String

If you're defining the function specifically to write to a file, you can just write its source code as a multi-line string. This is straightforward for simple functions:

# Define the function code as a string (make sure to preserve indentation!)
function_code = """def fun_one(x):
    print(x)
"""

with open('file.py', 'w') as file_handler:
    file_handler.write(function_code)

Why Your Original Code Failed

Just to clarify: file_handler.write(fun_one) passes the function object itself to write(), which converts it to its string representation (the weird <function...> text) instead of the actual code. Using either of the methods above will write the proper source code to your file.

内容的提问来源于stack exchange,提问作者user5208585

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:16:26