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 - Example: The following code writes a small sequence of bytes into a file called file.bin and then reads it back in binary mode. ... pathlib provides an object-oriented way to work with files and paths.
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
There are several ways to present the output of a program; data can be printed in a human-readable form, or written to a file for future use. This chapter will discuss some of the possibilities. Fa...
🌐
Programiz
programiz.com › python-programming › file-operation
Python File Operation (With Examples)
For example, Suppose we have a file named file2.txt. ... Now let's write to this file. # open the file2.txt in write mode file2 = open('file2.txt', 'w') # write new contents to the file2.txt file file2.write('Learning Python is interesting.\n') file2.write('File operations are useful.\n')
🌐
CodingNomads
codingnomads.com › python-write-to-file
Python: Write to File
In the code snippet above, you're opening a file called output.txt in write mode ("w") and assigning that to the variable file_out. If there's no file called output.txt in the directory you're running your script from, then it will be created. Note: If a file called output.txt already exists, all of its content will be instantly deleted if you open it up in write mode, as shown above. After opening the file, you can write data to it using the .write() method on your file_out variable:
Find elsewhere
🌐
LearnPython.com
learnpython.com › blog › write-to-file-python
How to Write to File in Python | LearnPython.com
Let’s run an example: # import import csv # Create header and data variables header = ['last_name', 'first_name', 'zip_code', 'spending'] data = ['Doe', 'John', 546000, 76] with open('customers.csv', 'w', encoding='UTF8', newline='') as file: ...
🌐
Scaler
scaler.com › home › topics › python › writing to file in python
Writing to File in Python - Scaler Topics
November 16, 2023 - Achieving this in Python is easily done by utilizing the open() function with the mode parameter set to 'a' (append). ... Without precaution, attempting to write to the file directly would result in overwriting these lines. However, using the 'a' mode in the open() function, we can append new data to the end of the file without affecting the existing content. Here's an example code ...
🌐
freeCodeCamp
freecodecamp.org › news › file-handling-in-python
File Handling in Python – How to Create, Read, and Write to a File
August 26, 2022 - Below is the code required to create, write to, and read text files using the Python file handling methods or access modes. In Python, you use the open() function with one of the following options – "x" or "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. Example ...
🌐
Codecademy
codecademy.com › article › handling-text-files-in-python
Handling Text Files in Python: How to Read from a File | Codecademy
The write() method allows us to write a single string to a file. It’s important to remember that write() does not add newline characters automatically, so we’ll need to insert \n if we want entries to appear on new lines. Let’s try understanding the write() method with the help of an example: ... Hello, world! Python is great! ... The above code opens the file example.txt in write mode, writes two lines of text (“Hello, world!” and “Python is great!”), and then automatically closes the file and erases any existing information.
🌐
GeeksforGeeks
geeksforgeeks.org › python › create-a-new-text-file-in-python
Create a New Text File in Python - GeeksforGeeks
July 23, 2025 - # Using open() function file_path = "new_file.txt" # Open the file in write mode with open(file_path, 'w') as file: # Write content to the file file.write("Hello, this is a new text file created using open() function.") print(f"File '{file_path}' created successfully.") ... In this example, in below code the Path class from the pathlib module to represent a file path named new_file_method3.txt.
🌐
DataCamp
datacamp.com › tutorial › python-write-to-file
Python Write to File: Working With Text, CSV, and JSON Files | DataCamp
January 21, 2026 - Run this script, and Python creates a file called example.txt in the same directory as your code. ... This works, but it’s not how you should write files long-term. Manually opening and closing files is easy to forget and easy to get wrong.
🌐
W3Schools
w3schools.com › python › python_file_handling.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
🌐
Tutorialspoint
tutorialspoint.com › python › python_write_to_file.htm
Python - Write to File
Python is a great language. Yeah its great!! By default, read/write operations on a file object are performed on text string data. If we need to handle files of different types, such as media files (mp3), executables (exe), or pictures (jpg), we must open the file in binary mode by adding the 'b' prefix to the read/write mode. To write binary data to a file, open the file in binary write mode ('wb'). The following example demonstrates this −
🌐
GeeksforGeeks
geeksforgeeks.org › python › file-handling-python
File Handling in Python - GeeksforGeeks
In Python, writing to a file is done using the mode "w". This creates a new file if it doesn’t exist, or overwrites the existing file if it does. The write() method is used to add content. After writing, make sure to close the file. Example: Writing to a file (overwrites if file exists)
Published   December 10, 2025