How to Write or Print to a File in Python
Python is a popular high-level programming language that is extensively used in industries for software development, data analysis, and machine learning. In Python, it’s essential to learn how to print or write data to a file, as it’s one of the most basic tasks that program needs to perform. In this article, we will discuss how to write or print data to a file in Python using different techniques.
1. Using Write()
Python offers a built-in function named “write()” that makes it easy to write data to a file. Here’s how to use it:
“`
# Open a file in write mode
file = open(“example.txt”, “w”)
# Write a string to the file
file.write(“Hello World.”)
# Close the file
file.close()
“`
In the above code, we have first opened the file “example.txt” in write mode using the open() built-in function. Next, we have used the write() method to insert the string “Hello World.” to the file. Finally, we have closed the file using the close() method.
2. Using Print() function
Python’s print() function can be used to write data to a text file by redirecting the standard output to the file. Here’s an example:
“`
# Open the file and redirect the standard output
with open(“example.txt”, “w”) as file:
print(“This is an example text file”, file=file)
“`
In the above code, the “with open()” statement creates a block to contain the working code. This block opens the file “example.txt” in “write” mode, and then the “print()” method is used to write “This is an example text file” to the file.
To write the output of the print function to a file, we redirect the output using the “file” parameter, which points the output to the file being opened in write mode.
3. Using the CSV module
Python has a built-in module named “csv,” which makes it easy to write data to a CSV file. Here’s how to use it:
“`
import csv
# Data to be written
data = [[‘Name’, ‘Roll No.’, ‘Grade’],
[‘Bella’, ‘101’, ‘A’],
[‘Elena’, ‘102’, ‘B’],
[‘David’, ‘103’, ‘C’]]
# Open the file and writer object
with open(‘example.csv’, ‘w’, newline=”) as file:
writer = csv.writer(file)
# Write data to the file
writer.writerows(data)
“`
In the above code, we have used the CSV module to write data to a CSV file. First, we have created a list of lists containing the data we want to write to the file. Then, we have opened the file in write mode and created a writer object using CSV module’s writer() function. Finally, we have written the data to the file using the writerow() method.