How To Quickly Create A File With Python

Hello Pythonistas, welcome back, today we will explore 2 ways to create a file with Python.

We will also see what’s the difference between write and append mode.

1. How do you create a file in Python with open()?

To create a file with the open() method:

f = open("new.txt", "w")
f.write("""I am writing something.
In Many Lines.""")
f.close()
  1. Create a variable to store the file object.
  2. Call the open() method with the file name and ‘w’ mode as arguments.
  3. Use the write() method on the variable to write anything.
  4. Close the file using the close() method.

2. How do you create a file in Python using the “with open” block?

Using this method to open a file allows you to not close the file after using it.

To create a file in Python using the “with open” block:

  1. Start the ‘with’ block.
  2. Call the open() method as shown before.
  3. Store the file object in a variable.
  4. Call the write() method on the file object
with open("new.txt", "w") as f:
    f.write("""something
In Multiple lines""")

How do I create a file with Python in a specific directory?

All the steps stay the same:

  1. Just give the full file path like: newFol/new.txt
  2. Ensure that the directory(folder) exists.
with open("newFol/new.txt", "w") as f:
    f.write("""something
In Multiple lines""")

How do you append to a text file in Python?

Instead of ‘w’ this time use ‘a’ (append) mode. This will add text at the end of the file.

with open("new.txt", "a") as f:
    f.write(""" add 
these lines too""")

Leave a Reply