如何在Python 3中将函数写入新文件?
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:
Method 1: Use the inspect Module (Recommended for Existing Functions)
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
withstatement is preferred over manually callingclose()because it handles file closure even if an error occurs. inspect.getsource()works for functions defined in.pyfiles, 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

