Python print() to File

To print to a file in Python, you can use the built-in open() function to open a file, and then use the write() method to write to it. Here is an example:

Python File Write

with open("example.txt", "w") as file: file.write("Hello, World!")
This will create a new file called "example.txt" in the current directory, and write the string "Hello, World!" to it. If the file already exists in the same path, then it will be overwritten. The with open statement is used to ensure that the file is properly closed after the block of code is executed, even if an error occurs. Also, the mode can be specified as a string, and it tells the function how you want to interact with the file. Here are the most commonly used file modes in Python:
  1. 'w': Write mode - This is used to create a new file or overwrite an existing file. If the file already exists, its previous content will be truncated (deleted).
  2. 'a': Append mode - This is used to open an existing file and add new content to the end of it. If the file does not exist in the path, it will be created.

Python file write

Using Python print()

You can also use print() function with file object as argument.
with open("example.txt", "w") as file: print("Hello, World!", file=file)
This will also create a file and write the string "Hello, World!" to it in a new line.

Python print()

The print() function in Python is used to output text or other data to the console. It can be used to print variables, strings, numbers, and other types of data. Additionally, print() function accept several optional parameters like end, sep, file, flush etc. to control the behaviour of the function.