Python Forum
Print/write to file function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Print/write to file function
#1
Hello All can someone help me with the below code. Ive been working to try and get the output printed to a file with the datetime but each route Ive tried I seem to get an error can anyone point out what I am doing wrong?

#! /usr/bin/python3.6

import pymysql
import datetime
date = str(datetime.date.today()-datetime.timedelta(1))
filename = datetime.datetime.now()
print(date)
 
 
 
try:
    db_con1 = pymysql.connect(host='nhmanpncblt01.xxx.xxx.com', port=3306, user='xxx', passwd='xxx', db='photonicnetworkcaptures')
    sql_select_Query = "select * from pncnetwork where startTime regexp \'^{}\'".format(date)
    db_con2 = pymysql.connect(host='nhmanpnckey01.xxx.xxx.com', port=3306, user='xxx', passwd='xxx', db='photonicnetworkcaptures')
    sql_select_Query = "select * from pncnetwork where startTime regexp \'^{}\'".format(date)
    db_con3 = pymysql.connect(host='nhmanpncfre01.xxx.xxx.com', port=3306, user='xxx', passwd='xxx', db='photonicnetworkcaptures')
    sql_select_Query = "select * from pncnetwork where startTime regexp \'^{}\'".format(date)
    db_con4 = pymysql.connect(host='NHMANPNCNE01.xxx.xxx.com', port=3306, user='xxx', passwd='xxx', db='photonicnetworkcaptures')
    sql_select_Query = "select * from pncnetwork where startTime regexp \'^{}\'".format(date)
    cursor1 = db_con1.cursor()
    cursor2 = db_con2.cursor()
    cursor3 = db_con3.cursor()
    cursor4 = db_con4.cursor()
    cursor1.execute(sql_select_Query)
    cursor2.execute(sql_select_Query)
    cursor3.execute(sql_select_Query)
    cursor4.execute(sql_select_Query)
    records1 = cursor1.fetchall()
    records2 = cursor2.fetchall()
    records3 = cursor3.fetchall()
    records4 = cursor4.fetchall()
    sys.stdout = open(filename.strftime("%d %B %Y")+".txt", "w")

    print ("Total number of rows in pncnetwork is: ", cursor1.rowcount + cursor2.rowcount + cursor3.rowcount + cursor4.rowcount)
    print ("\nPrinting each pncnetwork record")
    for row in records1:
        print("{}, {}".format("Beltway", row[2], row[3]))
    for row in records2:
        print("{}, {}".format("Keystone", row[2], row[3]))
    for row in records3:
        print("{}, {}".format("Freedom", row[2], row[3]))
    for row in records4:
        print("{}, {}".format("New England", row[2], row[3]))


except Exception as e:
    print("ERROR ", str(e))
 
finally:
    db_con1.close()
    db_con2.close()
    db_con3.close()
    db_con4.close()

sys.stdout.close()
./pncnetworktest.py
2020-03-31
ERROR name 'sys' is not defined
Traceback (most recent call last):
File "./pncnetworktest.py", line 55, in <module>
sys.stdout.close()
NameError: name 'sys' is not defined
Reply
#2
To use sys.stdout you need to import the sys package, but you have no need to call sys.stdout.close().

Next google "Python print to file" and you will learn all about files and how you create files and write to files.

One last thing, is 2020-03-31 a valid file name on your computer? If you want to write to a file you have to give the file a name that is compatible with your operating system. Make sure to give the file and appropriate extension so you can use the file outside your program or at least provide a hint about how the file is used.
Reply
#3
(Apr-01-2020, 03:43 PM)deanhystad Wrote: To use sys.stdout you need to import the sys package, but you have no need to call sys.stdout.close().

Next google "Python print to file" and you will learn all about files and how you create files and write to files.

One last thing, is 2020-03-31 a valid file name on your computer? If you want to write to a file you have to give the file a name that is compatible with your operating system. Make sure to give the file and appropriate extension so you can use the file outside your program or at least provide a hint about how the file is used.

Yes the name is the output of the last DB backup which I am checking. The code is running on a Linux machine so I can nano and open the file. So the last statement I can remove, will this theory work for printing the screen output to a file as is like or is this a more complicated way about it? Just asking as I’m very new to this. The python class I had attended was for python 2 not three so that’s where my biggest struggle is. All the ex soles I have appear not to work in 3
Reply
#4
Ooops! I missed sys.stdout = open(filename.strftime("%d %B %Y")+".txt", "w"). Even has a file extension. Hmmm, oh well.

So what isn't working? Is the file created? Does the file contain "Total number of rows in pncnetwork is:"? What do you see after that?

If the file is not created, is it a permissions problem? Where are you trying to create the file? Or are you getting an exception. A problem with redirecting stdout to a file is this doesn't work:
except Exception as e:
    print("ERROR ", str(e))
You would need to print that to stderr. If your really want to redirect stdout I would leave out exception handling until things are working.
Reply
#5
(Apr-01-2020, 04:57 PM)deanhystad Wrote: Ooops! I missed sys.stdout = open(filename.strftime("%d %B %Y")+".txt", "w"). Even has a file extension. Hmmm, oh well.

So what isn't working? Is the file created? Does the file contain "Total number of rows in pncnetwork is:"? What do you see after that?

If the file is not created, is it a permissions problem? Where are you trying to create the file? Or are you getting an exception. A problem with redirecting stdout to a file is this doesn't work:
except Exception as e:
    print("ERROR ", str(e))
You would need to print that to stderr. If your really want to redirect stdout I would leave out exception handling until things are working.

The file gets created however the data for number of rows, and also the rows caller out in the print line are not placed in the file, it’s just blank. I’m not sure what or where I did this incorrectly
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  failing to print not matched lines from second file tester_V 13 810 Apr-13-2021, 03:36 PM
Last Post: DeaD_EyE
  How can I write a function with three parameters? MehmetAliKarabulut 1 446 Mar-04-2021, 10:47 PM
Last Post: Larz60+
  print function output wrong with strings. mposwal 5 424 Feb-12-2021, 09:04 AM
Last Post: DPaul
  write mariadb table rows query to each file? shams 1 277 Feb-02-2021, 04:10 PM
Last Post: buran
  Read/Write binary file deanhystad 3 413 Feb-01-2021, 10:29 AM
Last Post: Larz60+
  Running A Parser In VSCode - And Write The Results Into A Csv-File apollo 5 636 Jan-14-2021, 08:58 PM
Last Post: snippsat
  Output with none, print(x) in function Vidar567 3 342 Nov-24-2020, 05:40 PM
Last Post: deanhystad
  How to write a code with İF function? Aycaaxx 1 324 Nov-03-2020, 05:46 AM
Last Post: deanhystad
  output correction using print() function afefDXCTN 2 1,808 Oct-13-2020, 12:58 PM
Last Post: cvilao
  get two characters, count and print from a .txt file Pleiades 9 787 Oct-05-2020, 09:22 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020