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.
Contents
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()
- Create a variable to store the file object.
- Call the open() method with the file name and ‘w’ mode as arguments.
- Use the write() method on the variable to write anything.
- 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:
- Start the ‘with’ block.
- Call the open() method as shown before.
- Store the file object in a variable.
- 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:
- Just give the full file path like:
newFol/new.txt
- 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""")
create a file with python