Discussion
Loading...

Post

  • About
  • Code of conduct
  • Privacy
  • About Bonfire
Trey Hunner 馃悕
@treyhunner@mastodon.social  路  activity timestamp 5 days ago

Python Tip #26 (of 365):

When opening a file, use a "with" block... especially for writing!

Using a "with" block to open a file will close it automatically when the "with" block exits: https://pym.dev/creating-and-writing-file-python/

So this:

with open("example.txt", mode="wt") as file:
file.write("An example file\n")

Is pretty much the same as this:

file = open("example.txt", mode="wt")
try:
file.write("An example file\n")
finally:
file.close()

馃У(1/4)

#Python #DailyPythonTip

Write to a file in Python

To write to a file in Python, you can use the built-in open function, specifying a mode of w or wt and then use the write method on the file object.
  • Copy link
  • Flag this post
  • Block
Log in

Bonfire Dinteg Labs

This is a bonfire demo instance for testing purposes. This is not a production site. There are no backups for now. Data, including profiles may be wiped without notice. No service or other guarantees expressed or implied.

Bonfire Dinteg Labs: About 路 Code of conduct 路 Privacy 路
Bonfire social 路 1.0.0 no JS en
Automatic federation enabled
  • Explore
  • About
  • Code of Conduct
Home
Login