{"id":265,"date":"2024-10-15T07:59:01","date_gmt":"2024-10-15T07:59:01","guid":{"rendered":"https:\/\/itsmycode.com\/?p=265"},"modified":"2024-10-15T07:59:02","modified_gmt":"2024-10-15T07:59:02","slug":"python-print-to-file","status":"publish","type":"post","link":"https:\/\/itsmycode.com\/python-print-to-file\/","title":{"rendered":"Python Print to File"},"content":{"rendered":"\n<p>We always use print statements in Python to display the output in the console or command line terminal. However, sometimes we want to change this behavior to print to a text file instead of the console.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"print-to-file-using-file-argument\">Print to file using file argument<\/h2>\n\n\n\n<p>The <strong><code>print()<\/code><\/strong> method accepts the file parameter as one of the arguments, and using this, we can print the standard output to a file.<\/p>\n\n\n\n<p>The default value of the file argument is <strong><code>sys.stdout<\/code><\/strong>, which prints the output on the screen.<\/p>\n\n\n\n<p><strong>Example 1: Print to the text file<\/strong><\/p>\n\n\n\n<p>The below program opens the <a href=\"https:\/\/itsmycode.com\/how-to-check-if-a-file-exists-in-python\/\" target=\"_blank\" rel=\"noreferrer noopener\">existing text file<\/a> in the write mode using the <strong><code>open()<\/code><\/strong> function (if file is not available it will <a href=\"https:\/\/itsmycode.com\/python-write-text-file\/\" target=\"_blank\" rel=\"noreferrer noopener\">create a new file<\/a>) and writes all the text specified inside the print statement. Once the content is written to a file, we close the file using the <strong><code>close()<\/code><\/strong> method.<\/p>\n\n\n\n<p><strong>Printing to a file<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Print to the text file\nfile = open('log.txt', 'w')\nprint('This is a sample print statement', file = file)\nprint('Hello World', file = file)\n\nfile.close()<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<p><strong>log.txt content<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>This is a sample print statement\nHello World<\/code><\/pre>\n\n\n\n<p><strong>Example 2: Print to the text file using inline file argument<\/strong><\/p>\n\n\n\n<p>If you want to control only a few print statements to output to a <strong><a href=\"https:\/\/itsmycode.com\/python-read-text-file\/\" target=\"_blank\" rel=\"noreferrer noopener\">text file<\/a><\/strong>, you could inline the file argument inside the print statement, as shown below.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Appends the print statement into a log.txt\n\nprint(\"Welcome to ItsMyCode\", file=open('log.txt','a'))\n<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<p><strong>log.txt content<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Welcome to ItsMyCode<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"redirecting-the-standard-output-stream-to-a-file\">Redirecting the Standard Output Stream to a file<\/h2>\n\n\n\n<p>Specifying the file argument helps debug the smaller programs but is not desirable in some situations.&nbsp;<\/p>\n\n\n\n<p>In this case, we can redirect all the standard output stream to a file. Setting the standard output to a file ensures that the text specified inside the <strong><code>print()<\/code><\/strong> function will be written to a file instead of displaying in the console.&nbsp;<\/p>\n\n\n\n<p>The standard output can be set in Python by importing the <strong><code>sys <\/code><\/strong>module and setting the <strong><em><code>stdout<\/code><\/em><\/strong> to a file or file-like object.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import sys\n\n# Prints in a console\/terminal\nprint('Default mode: Prints on a console.')\n\n# Store the reference of original standard output into variable\noriginal_stdout = sys.stdout \n\n# Create or open an existing file in write mode\nwith open('log.txt', 'w') as file:\n    # Set the stdout to file object\n    sys.stdout = file\n    print('File Mode: Print text to a file.')\n    \n    # Set the stdout back to the original or default mode\n    sys.stdout = original_stdout\n\nprint('Default Mode: Prints again on a console.')\n<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Inside a log.txt file<br><br><code>Hello Welcome to Python Tutorials !!!<br>File Mode: Print text to a file.<br><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">On a console\/terminal<br><br><code>Default mode: Prints on a console.<br>Default Mode: Prints again on a console.<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"redirect-the-python-script-output-to-file\">Redirect the Python Script Output to File<\/h2>\n\n\n\n<p>The easiest and dirty way is to redirect the Python script\u2019s output directly from the command line window while executing the script.&nbsp;<\/p>\n\n\n\n<p>For example, if you have a Python script file named <strong><code>main.py<\/code><\/strong> with the following code.<\/p>\n\n\n\n<p>We can redirect the output of the Python script using the <em><strong>right angle bracket<\/strong><\/em>, as shown below.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">python3 main.py &gt; output.txt&nbsp;&nbsp;<\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>print(\"Hello World !!!\")<\/code><\/pre>\n\n\n\n<p>If you open the <code>output.txt<\/code> file, you can see the below content written into the text file.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Output.txt file<br><code>Hello World !!!<\/code><\/pre>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>We always use print statements in Python to display the output in the console or command line terminal. However, sometimes we want to change this behavior to print to a text file instead of the console. Print to file using file argument The print() method accepts the file parameter as one of the arguments, and [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":266,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[11,1],"tags":[],"class_list":["post-265","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-files-and-folders","category-python"],"_links":{"self":[{"href":"https:\/\/itsmycode.com\/wp-json\/wp\/v2\/posts\/265","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/itsmycode.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/itsmycode.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/itsmycode.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/itsmycode.com\/wp-json\/wp\/v2\/comments?post=265"}],"version-history":[{"count":1,"href":"https:\/\/itsmycode.com\/wp-json\/wp\/v2\/posts\/265\/revisions"}],"predecessor-version":[{"id":267,"href":"https:\/\/itsmycode.com\/wp-json\/wp\/v2\/posts\/265\/revisions\/267"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/itsmycode.com\/wp-json\/wp\/v2\/media\/266"}],"wp:attachment":[{"href":"https:\/\/itsmycode.com\/wp-json\/wp\/v2\/media?parent=265"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/itsmycode.com\/wp-json\/wp\/v2\/categories?post=265"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/itsmycode.com\/wp-json\/wp\/v2\/tags?post=265"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}