Can't get code to write to text file in Python 3 - python-3.x

I am was tasked with commanding a multimeter from my computer using python and storing the information into a text file. I have tried altering the code in a million ways and I can not figure out what I am doing wrong. The file already exists in my computer but nothing ever gets displayed there.
import serial
import time
import math
import string
#setting up connection to Multimeter through COM6
ser = serial.Serial('COM6')
ser.baudrate = 9600
ser.bytesize = 8
ser.parity = 'N'
ser.stopbites = 1
ser.timeout = 1
class testing():
def test():
#getting user input
serialNum = input("Serial number: ")
date = input("Date: ")
time = input("Time: ")
x = 1
if x==1:
ser.write(b'meas:volt:dc?\r\n')
returnBytes = ser.readline()
fbytes = float(returnBytes)
#print("DC voltage: " + returnBytes)
ser.close()
return fbytes
#saving and printing information to text file
lines = [serialNum, date, time, fbytes]
file = open('/Users/myname/test.txt', 'w')
file.write(''.join(lines))
file.close()

I solved the problem i posted about, however the code is still spitting out an error that I am trying to solve. but for the sake of the question, this is what i revised my code to so that the information would display in the text file
import serial
import time
import math
import string
#setting up connection to Multimeter through COM6
ser = serial.Serial('COM6')
ser.baudrate = 9600
ser.bytesize = 8
ser.parity = 'N'
ser.stopbites = 1
ser.timeout = 1
#getting user input
serialNum = str(input("Serial number: "))
date = str(input("Date: "))
time = str(input("Time: "))
#getting measurement of DC voltage
ser.write(b'meas:volt:dc?\n') #'b' encodes info from meter to bytes
returnDC = ser.readline()
fbytesDC = float(returnDC)
#getting resistance measurement
ser.write(b'meas:res?\n') #'b' encodes info from meter to bytes
returnRes = ser.readline()
fbytesRes = float(returnRes)
#close the active port
ser.close()
#saving and printing information to text file
lines = [serialNum, date, time]
file = open("C:/Users/myname/test.txt", "a+")
file.write(' '.join(lines))
file.write(" DC voltage: "+ str(fbytesDC))
file.write(" Resistance: "+ str(fbytesRes))
file.write("\n")
file.close()

Related

Python script won't run over SSH but will run locally

I am writing a small application to monitor some temperatures using a raspberry pi. I would like to be able to remotely start or restart the monitoring script remotely. I connect via SSH, cd to the .py file's directory, and then i "python temp_controller.py &". This gives me an error importing something. "from w1thermsensor import W1ThermSensor". This error does not occur when running the script from Thonny directly on the Pi.
"Main" file.
import Send_Email
import Temp_Sensor
import os
import glob
import math
import timefuncs
import apc_controls
program_start_time = timefuncs.get_time() #Used to determine how long the program has been running.
printable_start_time = timefuncs.get_printable_time()
filename = ("Temperature Data " + printable_start_time.strftime("%c") + ".txt")
state = 0 #Used to switch between activities and determine if there has been an error.
temps = [0,0,0,0,0,0,0,0],[0,0] #Holds temperature data
over_temp_counter = 0 #variable for tracking consecutive over temp values
newdir = os.getcwd() + "/temps files"; os.chdir(newdir) #Changes directory to storage location for temperature files
with open(filename, "w+") as tempsfile:
tempsfile.write("Long Term Temperature Monitor Project\r\n")
tempsfile.write("Date-Time,Sensor ID,Sensor Name,Temperature\r\n")
test = 0
while True:
if (math.floor(timefuncs.get_time())) % 30 == 0 and state == 0:
print("sample")
state = 1 #stops this from executing multiple times per second
length = Temp_Sensor.read_sensors(temps) #gets number of sensors and sensor data with IDs
#Writes data line to log file
now = timefuncs.get_printable_time()
tempsfile.write("%s"%now)
i = 0
while i < length:
print("Sensor %s has temperature %.2f" % (temps[i][0], temps[i][1]))
tempsfile.write(",%s"%temps[i][0])
tempsfile.write(",%s"%Temp_Sensor.get_sensor_name(temps[i][0]))
tempsfile.write(",%f"%temps[i][1])
i += 1
tempsfile.write("\r\n")
#Checks temperatures to see if over temp
i = 0
over = False
while i < length:
if Temp_Sensor.check_temp(temps[i][1]):#if over temp
over = True
if over_temp_counter > 1:#ensures there is not a single fluke reading that causes error
print("over temp")
tempsfile.close()#close log file
Send_Email.send_fail_email(filename)#send email with log file
apc_controls.turn_off_apc()#shut down power to test
tempsfile = open("(After error" + printable_start_time.strftime("%c") + ".txt", "w+")
else:
print("increment over")
over_temp_counter += 1
i+=1
if over == False:
over_temp_counter = 0
elif (math.floor(timefuncs.get_time())) % 30 != 0:#if not 30 second increment reset blocker used to prevent the 30 secodn operations from occuring more than once
state = 0
File with the error.
import time
import glob
from w1thermsensor import W1ThermSensor
def read_sensors(data):
i = 0
j = 0
for sensor in W1ThermSensor.get_available_sensors([W1ThermSensor.THERM_SENSOR_DS18B20]):
data[i][j] = sensor.id
j+=1
data[i][j] = sensor.get_temperature()
i+=1
j = 0
return i
def get_sensor_name(id):
if id == "000009ac911f":
return "Sensor 1"
elif id == "000009aecc36":
return "Sensor 2"
def check_temp(value):
if value > 80:
return 1
else:
return 0
I guess on your local machine you did something like pip install w1thermsensor, right? You need to install the w1thermsensor dependency on your Raspberry pi too

Im trying to write to a file in a loop but it just seems to be writing nothing?

Here is the full code, it is for a basic random alphabetical shift encryption. For some reason, the .write() don't seem to be working.
from random import randint
import time
import os
sentence = input('What do you want to encrypt? ').lower()
namefile = input('What do you want to call the encrypted file? ')
alphabet = {'a':0,'b':1,'c':2,'d':3,'e':4,'f':5,'g':6,'h':7,'i':8,'j':9,'k':10,'l':11,'m':12,'n':13,'o':14,'p':15,'q':16,'r':17,'s':18,'t':19,'u':20,'v':21,'w':22,'x':23,'y':24,'x':25,' ':26,'.':27}
alphabet1 = {0:'a',1:'b',2:'c',3:'d',4:'e',5:'f',6:'g',7:'h',8:'i',9:'j',10:'k',11:'l',12:'m',13:'n',14:'o',15:'p',16:'q',17:'r',18:'s',19:'t',20:'u',21:'v',22:'w',23:'x',24:'y',25:'x',26:' ',27:'.'}
shift = randint(1,27)
x = len(sentence)
y = 0
encrypted_file = open(namefile + '.txt', 'wt')
while y < x:
letter = sentence[y]
position = alphabet[letter]
position = position + shift
if position > 27:
position = position - 27
letter = alphabet1[position]
Here is the first .write(). This one is inside a loop.
encrypted_file.write(letter)
y = y + 1
This is the second .write(). This is a single use one
encrypted_file.write('\nEncryption Shift = ' + str(shift))
encrypted_file.close
time.sleep(2)
print('Done')
time.sleep(1)
print('Here is your encrypted file.')
time.sleep(2)
os.startfile('C:/Users/Jedidiah/Documents/' + namefile + '.txt')
The mode key "wt" doesn't exist.
check here! for all proper mode keys
UPDATE: try this
from random import randint
import time
import os
sentence = input('What do you want to encrypt? ').lower()
namefile = input('What do you want to call the encrypted file? ')
alphabet = {'a':0,'b':1,'c':2,'d':3,'e':4,'f':5,'g':6,'h':7,'i':8,'j':9,'k':10,'l':11,'m':12,'n':13,'o':14,'p':15,'q':16,'r':17,'s':18,'t':19,'u':20,'v':21,'w':22,'x':23,'y':24,'x':25,' ':26,'.':27}
alphabet1 = {0:'a',1:'b',2:'c',3:'d',4:'e',5:'f',6:'g',7:'h',8:'i',9:'j',10:'k',11:'l',12:'m',13:'n',14:'o',15:'p',16:'q',17:'r',18:'s',19:'t',20:'u',21:'v',22:'w',23:'x',24:'y',25:'x',26:' ',27:'.'}
shift = randint(1,27)
x = len(sentence)
y = 0
encrypted_file = open(namefile + '.txt', 'a')
while y < x:
letter = sentence[y]
position = alphabet[letter]
position = position + shift
if position > 27:
position = position - 27
letter = alphabet1[position]
encrypted_file.write(letter)
y = y + 1
encrypted_file.write('\nEncryption Shift = ' + str(shift))
encrypted_file.close
time.sleep(2)
print('Done')
time.sleep(1)
print('Here is your encrypted file.')
time.sleep(2)
os.startfile('C:/Users/Jedidiah/Documents/' + namefile + '.txt')
if you want to overwrite the file use "w" for the mode key

Sending a file over a TCP server in a string

We need to send a pdf file over a TCP server in a string with the following format:
command number date size file
In the server, we're doing this:
l = f.read()
f.close()
user.sendall(("AQT " + "12345678 " + "16SET2015_12:00:00 " + str(size) + " " + l).encode('utf-8')
Our client looks like this:
quiz = s.recv(buff_size)
quiz_aux = quiz
while(quiz_aux):
quiz_aux = s.recv(buff_size)
quiz += quiz_aux
quiz = quiz.decode('utf-8')
response = quiz.split(" ", 4)
if response[0] == 'AQT':
QID = eval(response[1])
time = response[2]
size = eval(response[3])
file_name = topic + "QF" + "001" + ".pdf"
f = open(file_name, "w")
f.write(response[4])
f.close()
print("received file " + file_name)
We can't seem to get the encoding right, no matter what we try it doesn't work and it also doesn't seem to receive the entire file.
If somebody could help us we'd be truly grateful.
You're most likely opening your file in ASCII instead of BINARY mode. Thats why you do not receive the complete file as you never read the complete file in the first place.
with open(file,'rb') as f:
data = f.read() # reads the complete file.
Here're some flaws in your code:
the decode('utf-8') magic is not required as you'll most likely want to transfer your data byte-by-byte.
calling eval do parse an int is not secure, use int() instead.
storing large files in variables or passing large files to a single send/sendall call is highly inefficient. This is also true for receiving large amounts of data.
the protocol design is flawed. make sure your peer gets a hint about the message size pretty early.
Here's a working example of your code:
client:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import socket
import os
TCP_IP = '127.0.0.1'
TCP_PORT = 9999
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
with open(bigfile,'rb') as f:
f.seek(0, os.SEEK_END)
size = f.tell()
f.seek(0, os.SEEK_SET)
x = f.read()
s.sendall("AQT " + "12345678 " + "16SET2015_12:00:00 " + str(size) + " " + x)
s.close()
server:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 9999
buff_size = 1024*8
topic = "xyz"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
print "ready"
conn, addr = s.accept()
print 'Connection address:', addr
quiz = conn.recv(buff_size)
quiz_aux = quiz
while(quiz_aux):
quiz_aux = conn.recv(buff_size)
quiz += quiz_aux
response = quiz.split(" ", 4)
print len(response)
if response[0] == 'AQT':
QID = int(response[1])
time = response[2]
size = int(response[3])
file_name = topic + "QF" + "001" + ".txt"
f = open(file_name, "wb")
f.write(response[4])
f.close()
print("received file " + file_name)
conn.close()

How format my data in category in python

a python program to read the rainfall.txt file and then write out a new file
called rainfallfmt.txt . The data should be grouped on the total annual rainfall field into
the following categories: [60-70], [71-80], [81-90],[91-]. Under each category, the new
file should format each line so that the city is right-justified in a field that is 25 characters wide, and the rainfall data should be printed in a field that is 5 characters wide with 1 digit to the right of the decimal point.
This is what I have so far;
the problem is I don't know how to categorize it?
Would you please help me and let me know how I can solve this problem?
================================================
# read the rainfall.txt then write out a new file called rainfall.txt
# the data should be grouped on the total annual rainfall field into the
# categories: [60-70], [71-80], [81,90], [91-]
import os.path
def main():
endofprogram = False
try:
InputFileName = input('Enter name of input file: ')
infile = open(InputFileName,'r')
OutputFileName = input('Enter name of output file: ')
# determine wether name exists
while True:
if os.path.isfile(OutputFileName):
OutputFileName = input('File Exists. Enter name again: ')
else:
outfile = open(OutputFileName,'w')
break
except IOError:
print("Error opening file - End of program")
endofprogram = True
#If there is not exception, start reading the input file
#Write the same data in formated form in new file.
if endofprogram == False:
data = []
for line in infile:
.
.# I dont know what to do in here!
.
outfile.write(data[0])
main()
# read the rainfall.txt then write out a new file called rainfall.txt
# the data should be grouped on the total annual rainfall field into the
# categories: [60-70], [71-80], [81,90], [91-]
import os.path
def main():
endofprogram = False
try:
InputFileName = input('Enter name of input file: ')
infile = open(InputFileName,'r')
OutputFileName = input('Enter name of output file: ')
# determine wether name exists
while True:
if os.path.isfile(OutputFileName):
OutputFileName = input('File Exists. Enter name again: ')
else:
outfile = open(OutputFileName,'w')
break
except IOError:
print("Error opening file - End of program")
endofprogram = True
#If there is not exception, start reading the input file
#Write the same data in formated form in new file.
if endofprogram == False:
cat_60 = []
cat_71 = []
cat_81 = []
cat_91 = []
for line in infile:
city, rain = line.split(' ')
rain = float(rain)
if 60 <= rain < 70:
cat_60.append((city, rain)) # Storing a tuple in the list
elif 70 <= rain < 80:
cat_71.append((city, rain))
elif 80 <= rain < 90:
cat_81.append((city, rain))
elif 90 <= rain :
cat_91.append((city, rain))
outfile.write("[60-70]"+'\n')
for i in range(len(cat_60)):
city = cat_60[i][0]
rain = cat_60[i][1]
outfile.write('%+25s'%(city)+'%5.1f'%(rain)+'\n')
outfile.write("[70-80]"+'\n')
for i in range(len(cat_71)):
city = cat_71[i][0]
rain = cat_71[i][1]
outfile.write('%+25s'%(city)+'%5.1f'%(rain)+'\n')
outfile.write("[80-90]"+'\n')
for i in range(len(cat_81)):
city = cat_81[i][0]
rain = cat_81[i][1]
outfile.write('%+25s'%(city)+'%5.1f'%(rain)+'\n')
outfile.write("[91-]"+'\n')
for i in range(len(cat_91)):
city = cat_91[i][0]
rain = cat_91[i][1]
outfile.write('%+25s'%(city)+'%5.1f'%(rain)+'\n')
main()
You can use split to separate the line in fields (it returns a list of strings), then take the rainfall, convert it to float, and use a list per category to store the data.
cat_60 = []
cat_71 = []
cat_81 = []
cat_91 = []
for line in infile:
city, rain = line.split(' ') # Spliting using blank as separator
rain = float(rain)
if 60 <= rain <= 70: # This works in Python as expected but don't in most other languages
cat_60.append((city, rain)) # Storing a tuple at the end of the list
elif 71 <= rain <= 80:
cat_71.append((city, rain))
# etc...
After that you can iterate in the categories and format the output with str.format() or using the % operator.
There are other things you can do to make your code more Pythonic, for example variable names should be snakecase, names in titlecase should be reserved for classes and uppercase for constants and instead of using a flag variable you can use and exit() to end the program.
You can do the following to call main() only if the file is invoked as a script:
if __name__ == '__main__':
main()

Python 3.3 cypher script

So i have this code here in python 3.3, it cyphers text with the ceaser cypher.
What i need to know is how do i make a script that will convert it back from the original so that the person i send it too can read it.
message = input("Input: ")
key = 11
coded_message = ""
for ch in message:
code_val = ord(ch) + key
if ch.isalpha():
if code_val > ord('z'):
code_val -= ord('z') - ord('a')
coded_message = coded_message + chr(code_val)
else:
coded_message = coded_message + ch
# print ("Input: " + message)
print ("Output: " + coded_message)
One more thing, I plan to be putting this is a tkinter message box, with the two entry fields used for the input and output. one field should be used to type what i want to convert and the other should be used to show what the text looks like after it has been crypted. The button should start the encryption. here is the code:
import sys
from tkinter import *
def mHello():
mLabel = Label(mGui,text = input("Hello World"))
mLabel.grid(row=3, column=0,)
mGui = Tk()
ment = StringVar()
mGui.geometry("450x450+250+250")
mGui.title("My TKinter")
# input label
mLabel = Label(mGui,text = "Input",)
mLabel.grid(row=1,column=0,)
# output label
mLabeltwo = Label(mGui,text = "Input",)
mLabeltwo.grid(row=2,column=0,)
# convert button
mButton = Button(text = "Convert",command = mHello)
mButton.grid(row=3,column=0)
# input entry
mEntry = Entry(mGui,textvariable=ment)
mEntry.grid(row=1,column=1)
# output entry
mEntryTwo = Entry(mGui,textvariable=ment)
mEntryTwo.grid(row=2,column=1)
mGui.mainloop()
By the way i am only 15 and this is my 2nd day learning python.
Some credit goes to sources on this forum that have provided me with some code snippets
Thank-you in advance guys!
Before i say anything else you should be aware that minds much greater the mine have advised against writing your own cypher script for anything other then learning
If you want them to be able to decode your code then provide them with a key. so in your case:
s maps to h
t maps to i
f maps to t
I hope this code illustrates my suggestion:
In [1]: from cyro import your_cyrptic_function
In [2]: key = {'s':'h', 't':'i', 'f':'t'}
In [3]: secret_word = your_cyrptic_function('hit')
In [4]: decyrpted_secret_word = ''
In [5]: for letter in secret_word:
decyrpted_secret_word += key[letter]
...:
In [6]: print(decyrpted_secret_word)
hit
For the code above i turned your original code into a function:
def your_cyrptic_function(secret):
message = secret
key = 11
coded_message = ""
for ch in message:
code_val = ord(ch) + key
if ch.isalpha():
if code_val > ord('z'):
code_val -= ord('z') - ord('a')
coded_message = coded_message + chr(code_val)
else:
coded_message = coded_message + ch
# print ("Input: " + message)
return coded_message
there are several great ways to do this in python. If your interested in cyptopgraphy then check out Udacities class cs387 applied cryptography

Resources