Seems to me like you need a basic computer usage course first before you move on to programming. Take like 1 or 2 days to learn the basics such as what files are, what file extensions are, what directories are, how to cut, copy and paste things, what computer programs are, what an operating system is, what the internet is, internet browser, search engine, maybe a few other concepts, and then you will be good to go. Answer from xxxHalny on reddit.com
🌐
W3Schools
w3schools.com › python › python_file_write.asp
Python File Write
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST TOOLS · Python HOME Python Intro Python Get Started Python Syntax ... Python Variables Variable Names Assign Multiple Values Output Variables Global Variables Variable Exercises Code Challenge Python Data Types
🌐
GeeksforGeeks
geeksforgeeks.org › python › writing-to-file-in-python
Writing to file in Python - GeeksforGeeks
December 27, 2025 - Opening a file in write mode ("w") clears any existing content before writing new data. This is useful when you want to start fresh and replace old information with new output. Example: This code writes two lines to file.txt, overwriting any previous content.
Top answer
1 of 5
16

You could just use a multiline string:

Copyimport os
filepath = os.getcwd()
def MakeFile(file_name):
    temp_path = filepath + file_name
    with open(file_name, 'w') as f:
        f.write('''\
def print_success():
    print "sucesss"        
''')
    print 'Execution completed.'

If you like your template code to be indented along with the rest of your code, but dedented when written to a separate file, you could use textwrap.dedent:

Copyimport os
import textwrap

filepath = os.getcwd()
def MakeFile(file_name):
    temp_path = filepath + file_name
    with open(file_name, 'w') as f:
        f.write(textwrap.dedent('''\
            def print_success():
                print "sucesss"        
                '''))
    print 'Execution completed.'
2 of 5
13
Copylines = []
lines.append('def print_success():')
lines.append('    print "sucesss"')
"\n".join(lines)

If you're building something complex dynamically:

Copyclass CodeBlock():
    def __init__(self, head, block):
        self.head = head
        self.block = block
    def __str__(self, indent=""):
        result = indent + self.head + ":\n"
        indent += "    "
        for block in self.block:
            if isinstance(block, CodeBlock):
                result += block.__str__(indent)
            else:
                result += indent + block + "\n"
        return result

You could add some extra methods, to add new lines to the block and all that stuff, but I think you get the idea..

Example:

Copyifblock = CodeBlock('if x>0', ['print x', 'print "Finished."'])
block = CodeBlock('def print_success(x)', [ifblock, 'print "Def finished"'])
print block

Output:

Copydef print_success(x):
    if x>0:
        print x
        print "Finished."
    print "Def finished."
🌐
Python documentation
docs.python.org › 3 › tutorial › inputoutput.html
7. Input and Output — Python 3.14.3 documentation
Strings can easily be written to and read from a file. Numbers take a bit more effort, since the read() method only returns strings, which will have to be passed to a function like int(), which takes a string like '123' and returns its numeric value 123. When you want to save more complex data types like nested lists and dictionaries, parsing and serializing by hand becomes complicated. Rather than having users constantly writing and debugging code to save complicated data types to files, Python allows you to use the popular data interchange format called JSON (JavaScript Object Notation).
🌐
freeCodeCamp
freecodecamp.org › news › file-handling-in-python
File Handling in Python – How to Create, Read, and Write to a File
August 26, 2022 - In Python, you use the open() function ... "w" – to create a new file: "x" – Create: this command will create a new file if and only if there is no file already in existence with that name or else it will return an error.
Find elsewhere
🌐
Real Python
realpython.com › run-python-scripts
How to Run Your Python Scripts and Code – Real Python
February 25, 2026 - Script mode runs code from files sequentially, while interactive mode uses the REPL for execution and testing with immediate feedback. Unix systems require executable permissions and a shebang line like #!/usr/bin/env python3 to run scripts directly as programs.
🌐
W3Schools
w3schools.com › python › python_file_open.asp
Python File Open
Python Overview Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods Python File Methods Python Keywords Python Exceptions Python Glossary · Built-in Modules Random Module Requests Module Statistics Module Math Module cMath Module · Remove List Duplicates Reverse a String Add Two Numbers · Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... Hello! Welcome to demofile.txt This file is for testing purposes.
🌐
Visual Studio Code
code.visualstudio.com › docs › python › python-tutorial
Getting Started with Python in VS Code
November 3, 2021 - Ensure your new environment is selected by using the Python: Select Interpreter command from the Command Palette. Note: For additional information about virtual environments, or if you run into an error in the environment creation process, see Environments. From the File Explorer toolbar, select the New File button on the hello folder: Name the file hello.py, and VS Code will automatically open it in the editor:
🌐
Programiz
programiz.com › python-programming › file-operation
Python File Operation (With Examples)
Python allows us to open files ... read the content, not modify it). Note: By default, Python files are open in read mode. Hence, the code open("file1.txt", "r") is equivalent to open("file1.txt")....
🌐
Guru99
guru99.com › home › python › how to create (write) text file in python
How to Create (Write) Text File in Python
August 12, 2024 - The output we want to iterate in the file is “this is line number”, which we declare with Python write file function and then percent d (displays integer) So basically we are putting in the line number that we are writing, then putting it in a carriage return and a new line character ... You can also append/add a new text to the already existing file or a new file. ... Once again if you could see a plus sign in the code, it indicates that it will create a new file if it does not exist.
🌐
GeeksforGeeks
geeksforgeeks.org › file-handling-python
File Handling in Python - GeeksforGeeks
It ensures that file is properly closed after its suite finishes, even if an exception is raised. with open() as method automatically handles closing the file once the block of code is exited, even if an error occurs. This reduces the risk of file corruption and resource leakage. ... Hello, World! Appended text. It's important to handle exceptions to ensure that files are closed properly, even if an error occurs during file operations. ... Hello, World! Appended text. Versatility : File handling in Python allows us to perform a wide range of operations, such as creating, reading, writing, appending, renaming and deleting files.
Published   January 14, 2025
🌐
PythonForBeginners
pythonforbeginners.com › home › reading and writing files in python
Reading and Writing Files in Python - PythonForBeginners.com
December 3, 2021 - In Python, write to file using the open() method. You’ll need to pass both a filename and a special character that tells Python we intend to write to the file. Add the following code to write.py.
🌐
Kite
kite.com › python › answers › how-to-import-a-python-file-in-the-source-code-directory-in-python
How to import a Python file in the source code directory in ...
Kite is a free autocomplete for Python developers. Code faster with the Kite plugin for your code editor, featuring Line-of-Code Completions and cloudless processing.
🌐
Real Python
realpython.com › read-write-files-python
Reading and Writing Files in Python (Guide) – Real Python
September 23, 2022 - In this tutorial, you'll learn about reading and writing files in Python. You'll cover everything from what a file is made up of to which libraries can help you along that way. You'll also take a look at some basic scenarios of file usage as well as some advanced techniques.
🌐
GeeksforGeeks
geeksforgeeks.org › python › reading-writing-text-files-python
Reading and Writing to text files in Python - GeeksforGeeks
Text files: Each line of text is terminated with a special character called EOL (End of Line), which is new line character ('\n') in Python by default. Binary files: There is no terminator for a line and data is stored after converting it into machine-understandable binary format. This article focuses on opening, closing, reading and writing data in a text file. Here, we will also see how to get Python output in a text file.
Published   September 24, 2025
🌐
Stack Overflow
stackoverflow.com › questions › 65268814 › how-to-copy-code-from-a-text-file-to-a-py-file
python - How to copy code from a text file to a .py file? - Stack Overflow
yes ... simpler way is to read the config data from the txt file ... copying to a py file seems pointless ... A Python script file is a text file.
🌐
Visual Studio Code
code.visualstudio.com › docs › python › run
Running Python code in Visual Studio Code
November 3, 2021 - After installing a Python interpreter on your machine, you can interact with the Python REPL by opening the terminal or command prompt on your system, and typing python (Windows) or python3 (macOS/Linux) to activate the Python REPL, notated by >>>. There are two additional ways you can interact with a Python REPL in VS Code.