<tutorialjinni.com/>

Python Write to File

Posted Under: Programming, Python, Tutorials on Nov 7, 2024

Python Write to File

To write text to a file in Python, use the `open` function with the `'w'` mode. This will overwrite the file if it already exists or create a new one.
# Writing text to a file
with open("example.txt", "w") as file:
    file.write("Hello, world!")

Python Write Line

The `writelines` method can be used to write multiple lines to a file.
 
# Writing multiple lines to a file
lines = ["First linen", "Second linen", "Third linen"]
with open("example_lines.txt", "w") as file:
    file.writelines(lines)

Python Write JSON to File

Use the `json` module to write JSON data to a file.
 
import json
# Writing JSON data to a file
data = {"name": "Alice", "age": 30, "city": "New York"}
with open("data.json", "w") as file:
    json.dump(data, file)

Python Write to CSV

The `csv` module makes it easy to write CSV files.
import csv

# Writing data to a CSV file
data = [["Name", "Age", "City"], ["Alice", 30, "New York"], ["Bob", 25, "Los Angeles"]]
with open("data.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerows(data)

Python Write String to File

You can directly write a string to a file using the `write` method.
# Writing a string to a file
text = "This is a sample text."
with open("string.txt", "w") as file:
    file.write(text)

Python Write List to File

A list can be written line-by-line using a loop or by using `writelines`.
 
# Writing a list to a file
my_list = ["apple", "banana", "cherry"]
with open("list.txt", "w") as file:
    for item in my_list:
        file.write(f"{item}n")

Python Write Bytes to File

To write binary data, use `'wb'` mode. This is useful for writing bytes directly to a file.
# Writing bytes to a file
data = b"x00x01x02x03"
with open("binary.bin", "wb") as file:
    file.write(data)

Python Write Dict to File

A dictionary can be written to a file as JSON or using the `str` representation.
 
# Writing a dictionary to a file as JSON
data = {"key1": "value1", "key2": "value2"}
with open("dict.txt", "w") as file:
    file.write(str(data))



imgae