write to a file in python

To write to a file in python, you can follow these steps:

  1. Open the file in write mode using the open() function.
  2. Use the .write() method to write to the file.
  3. Close the file using the .close() method.

Here's an example code snippet that demonstrates this:

main.py
# Open file in write mode
file = open("filename.txt", "w")

# Write to the file
file.write("This is some sample text.")

# Close the file
file.close()
151 chars
9 lines

In this example, we opened a file named filename.txt in write mode using the open() function. Then, we wrote the text "This is some sample text." to the file using the .write() method. Finally, we closed the file using the .close() method to free up system resources.

related categories

gistlibby LogSnag