Save Data in a Column Python DS18B20 - python

My Python code for data saves data of a temperature sensor(DS18B20) but doesn't save the Temperature in a column. The Temperature is written in a line like that: ['25.25']. Can somebody please tell me how to fix it. I have to separate the read Temperature from the Sensor into several Numbers. Thanks for your help
while programmStatus == 1:
#while True:
now = datetime.now(timezoneBerlin)
#while True:
# open new file
with open ( 'test.tsv', 'w') as f:
for temperature_single in Temperature:
f.write ("{:>5}\n".format('Temperature'))
f.write("\t{:>5}\n".format
(format(temperature_single)))
f.write("\n")
f.flush()
f.close()
x = 0
ds1820readout()
print ("Sensorname und Temperaturevalue:")
while x < tempSensorQuantity:
print (tempSensorName[x] , " " , tempSensorValue[x], " °C")
x = x + 1
print ("\n")
In this code, there is an I/0 error on closed file, can somebody please help?

It seems that Temperature is a list of values. If you try to put them into the csv you have to iterate over the list first, e.g.:
tempSensorName = []
tempSensorQuantity = 0
tempSensorValue = []
programmStatus = 1
Temperature = tempSensorValue
def ds1820einlesen():
global tempSensorName, tempSensorQuantity, programmStatus
def ds1820auslesen():
global tempSensorName, tempSensorQuantity, tempSensorValue,
with open ( 'test.tsv', 'w') as f:
for temperature_single in Temperature:
f.write ("{:>5}\n".format('Temperature'))
f.write("\t{:>5}\n".format(format(temperature_single)))
f.write("\n")
f.flush()
f.close()
x = 0
ds1820auslesen()
print ("Sensorname and Temperaturevalue:")
while x < tempSensorQuantity:
print (tempSensorName[x] , " " ,
tempSensorValue[x], " °C")
x = x + 1
print ("\n")

Related

How can you write to a text file in python 3?

Could someone please explain why this code won't write to a text file?
I run the code but a text file is not created and also cannot be opened using f.open("data.txt","r")
f = open("data.txt", "w+")
n = 1
s = 0
for n in range(1, 999999):
s += 1/n**2
print(s, end="\r")
x = s*6
pisquare = math.sqrt(x)
f.write("Pi is ", pisquare)
f.close()
The recommended way to open and write to a file is as follow:
with open(file_path, 'w') as file:
file.write(f'Pi is {pisquare}')
We use the context manager with so the file closes automatically when done with .write(). This prevents memory corruption when your program exits prematurely I believe.
However, as you have probably noticed, your problem comes from this line:
f.write("Pi is ", pisquare)
You are giving .write() two arguments rather than one string.
import math
f = open("data.txt", "w+")
n = 1
s = 0
for n in range(1, 999999):
s += 1/n**2
print(s, end="\r")
x = s*6
pisquare = math.sqrt(x)
f.write("Pi is " + str(pisquare))
f.close()
I am able to create the text file. Please check for it in your current directory. But if I understand your code correctly, this is what you are looking for -
import math
n = 1
s = 0
with open("data.txt", "w+") as f:
for n in range(1, 9999):
s += 1/n**2
print(s, end="\r")
x = s*6
pisquare = math.sqrt(x)
f.write(" Pi is " + str(pisquare) + "\n")

Python coding for opening and saving data to a file

I am having an issue getting the train function to work correctly in python. I can not modify the def function. I am at the point where I need to get the second file to read lines one at a time for PosList and i need to match the value of movieWordCount[z] in OpenPos. If the file is there, then I am good to incrment column 2 by one of t hat line (segmented by a space). If it is not, then I need the else to append it to the file end. It does not work. It does not append the values if it is missing and I am not sure if it will find the value if it is there. I have been stuck getting thsi to work for two days.
Here is my code segment I am working with:
with open("PosList") as OpenPos:
lines = OpenPos.readlines()
print lines
if movieWordCount[z] in lines:
print "found"
#Now use tokenize to split it apart by space and set to new array for me to call column2
else:
print "not found"
lines.append(movieWordCount[z] + " 1" + "\n")
Here is my full code:
#!/usr/bin/python
#Import Counter
import collections
from collections import Counter
#Was already here but pickle is used for data input and export
import math, os, pickle, re
class Bayes_Classifier:
def __init__(self, trainDirectory = "movie_reviews/"):
#If file listing exists skip to train
if os.path.isfile('iFileList'):
print "file found"
self.train()
#self.classify()
#If file listing does not exist skip to train
if not os.path.isfile('iFileList'):
print "no file"
newfile = 'iFileList'
tempList = set()
subDir = './movie_reviews'
for filenames in os.listdir(subDir):
my_sub_path = os.path.join(os.sep,subDir,filenames)
tempList.add(filenames)
self.save("filenames", "try3")
f = []
for fFileObj in os.walk("movie_reviews/"):
f.extend(fFileObj)
break
pickle.dump(f, open( "save.p", "wb" ))
self.save(f, "try4")
with open(newfile, 'wb') as fi:
pickle.dump(tempList, fi)
#print tempList
self.train()
#self.classify()
def train(self):
'''Trains the Naive Bayes Sentiment Classifier.'''
print "File ready for training"
#Open iFileList to use as input for opening movie files
x = 0
OpenIFileList = open('iFileList','r')
print "iFileList now Open"
#Loop through the file
for line in OpenIFileList:
#print "Ready to read lines"
#print "reading line " + line
if x > 4:
if x % 2 == 0:
#print line
s = line
if '-' in s:
comp = s.split("'")
#print comp[2]
print comp[1] #This is What you need for t he movie file
compValue1 = comp[1]
#Determine Positive/Negative.
#compType is the variable I am storing it to.
compType = compValue1.split("-",2)[1]
#print compType #Prints that middle value like 5 or 1
# This will do the work based on the value.
if compType == '5':
# print "you have a five" #Confirms the loop I am in.
#If file does not exists create it
if not os.path.exists('PosList'):
print "no file"
file('PosList', 'w').close()
#Open file that needs to be reviewed for word count
compValue2 = "movie_reviews/" + compValue1
print compValue2 #Prints the directory and file path
OpenMovieList = open(compValue2,'r')
for commentLine in OpenMovieList:
commentPositive = commentLine.split(" ")
commentPositiveCounter = Counter(commentPositive)
#print commentPositiveCounter # " Comment Pos goes here"
#if commentLine != '' or commentLine != ' ':
#Get first word, second word, ....
if commentLine and (not commentLine.isspace()):
movieWordCount = self.tokenize(commentLine)
y = len(movieWordCount) #determines length of string
print y
z = 0
#print movieWordCount[0] # Shows the zero position in the file.
while z < y:
print "position " + str(z) + " word is " + movieWordCount[z] # Shows the word we are at and position id
with open("PosList") as OpenPos:
lines = OpenPos.readlines()
print lines
if movieWordCount[z] in lines:
print "found"
else:
print "not found"
lines.append(movieWordCount)
z = z + 1
#Close the files
OpenMovieList.close()
OpenPos.close()
x += 1
#for line2 in OpenIFileList.readlines():
#for line in open('myfile','r').readlines():
#do_something(line)
#Save results
#Close the File List
OpenIFileList.close()
def loadFile(self, sFilename):
'''Given a file name, return the contents of the file as a string.'''
f = open(sFilename, "r")
sTxt = f.read()
f.close()
return sTxt
def save(self, dObj, sFilename):
'''Given an object and a file name, write the object to the file using pickle.'''
f = open(sFilename, "w")
p = pickle.Pickler(f)
p.dump(dObj)
f.close()
def load(self, sFilename):
'''Given a file name, load and return the object stored in the file.'''
f = open(sFilename, "r")
u = pickle.Unpickler(f)
dObj = u.load()
f.close()
return dObj
def tokenize(self, sText):
'''Given a string of text sText, returns a list of the individual tokens that
occur in that string (in order).'''
lTokens = []
sToken = ""
for c in sText:
if re.match("[a-zA-Z0-9]", str(c)) != None or c == "\'" or c == "_" or c == '-':
sToken += c
else:
if sToken != "":
lTokens.append(sToken)
sToken = ""
if c.strip() != "":
lTokens.append(str(c.strip()))
if sToken != "":
lTokens.append(sToken)
return lTokens
To open a file for writing, you can use
with open('PosList', 'w') as Open_Pos
As you are using the with form, you do not need to close the file; Python will do that for you at the end of the with-block.
So assuming that the way you add data to the lines variable is correct, you could remove the superfluous code OpenMovieList.close() and OpenPos.close(), and append 2 lines to your code:
with open("PosList") as OpenPos:
lines = OpenPos.readlines()
print lines
if movieWordCount[z] in lines:
print "found"
else:
print "not found"
lines.append(movieWordCount)
with open("PosList", "w") as OpenPos:
OpenPos.write(lines)

loop iteration - rewriting the output file

I currently have this code that successfully reads information from two sources and correctly formats them into an output file \_spec_final.t15. Currently the information prints one after another, but I would like it to print the information for one line/file then overwrite it with the next iteration. Does anybody know how to do this?
with open('\\_spec_final.t15', 'w') as f:
with open('info.txt', 'rt') as infofile:
for count, line in enumerate(infofile):
print count
lat = float(line[88:94])
lon = float(line[119:127])
year = int(line[190:194])
month = int(line[195:197])
day = int(line[198:200])
hour = int(line[201:203])
minute = int(line[204:206])
second = int(line[207:209])
dur = float(line[302:315])
numpoints = float(line[655:660])
fov = line[481:497] # field of view?
sza = float(line[418:426])
snr = 0.0000
roe = 6396.2
res = 0.5000
lowwav = float(lowwav)
highwav = float(highwav)
spacebw = (highwav - lowwav)/ numpoints
d = datetime.datetime(year, month, day, hour, minute, second)
f.write('{:>12.5f}{:>12.5f}{:>12.5f}{:>12.5f}{:>8.1f}'.format(sza,roe,lat,lon,snr)) # line 1
f.write("\n")
f.write('{:>10d}{:>5d}{:>5d}{:>5d}{:>5d}{:>5d}'.format(year,month,day,hour,minute,second)) # line 2
f.write("\n")
f.write( ('{:%Y/%m/%d %H:%M:%S}'.format(d)) + "UT Solar Azimuth:" + ('{:>6.3f}'.format(sza)) + " Resolution:" + ('{:>6.4f}'.format(res)) + " Duration:" + ('{:>6.2f}'.format(dur))) # line 3
f.write("\n")
f.write('{:>21.13f}{:>26.13f}{:>24.17e}{:>12f}'.format(lowwav,highwav,spacebw,numpoints)) # line 4
f.write("\n")
with open(files[count], 'r') as g:
for line in g:
wave_no, intensity = [float(item) for item in line.split()]
if lowwav <= wave_no <= highwav:
f.write(str(intensity) + '\n')
Open and write to the file after you read in infofile.
It will open and overwrite \_spec_final.t15 with each iteration.
with open('info.txt', 'rt') as infofile:
for count, line in enumerate(infofile):
print count
with open('\\_spec_final.t15', 'w') as f:

Write to file and print to screen out of step with each other

I have a problem with writing to file.
What seems to happen is that a program prints numbers to screen in the order 0,1,2,3 (zeroth, first, second, third) but writes to file in the order -1, 0, 1, 2. Even when the print to screen command follows the write to file command.
Sample code follows. Any ideas how to make it write to file in order 0,1,2,3?
Many thanks - Scriptham.
import random
import time
ln = 4
mins = 10
j = 0
n_sensor = 0
temp_c = 0
data_file = "/home/pi/laboratory/test.csv"
def read_temp():
temp_c = 100 * random.random()
return str("%.3f"% temp_c)
for j in range (1,mins):
f = open(data_file,'a')
f.write("\n" + str(j))
f.close
for n_sensor in range (0,ln):
#device_file_1 =
print("A " + str(n_sensor))
x = read_temp()
f = open(data_file, 'a')
f.write("," + x)
f.close
print("OP temp_c = ", x)
#time.sleep(0.5)
time.sleep(10) #normally would be 59.5 or 60 or similar
quit()
The problem is most likely that you're opening the output file dozens of times, but never closing it.
You should do f = open(data_file,'a') before the loop and only once. Then when everything's done, call f.close() (f.close is not the same as f.close()!).
To make sure the file is always closed, you should use the with statement.
For example:
with open(data_file, 'a') as f:
f.write("\n" + str(j))
This will close the file, even if an exception happens during the write.
Alternatively, you need to use something like:
f = open(data_file, 'a')
try:
f.write("\n" + str(j))
finally:
f.close()

Copy 'N' lines from one file to another in python?

Essentially what I am attempting to do is read 'n' number of lines from a file and then write them to a separate file. This program essentially should take a file that has 100 lines and separate that file into 50 separate files.
def main():
from itertools import islice
userfile = raw_input("Please enter the file you wish to open\n(must be in this directory): ")
file1 = open(userfile, "r+")
#print "Name: ", file1.name
#print "Closed or not", file1.closed
#print "Opening mode: ", file1.mode
#print "Softspace flag: ", file1.softspace
jcardtop = file1.read(221);
#print jcardtop
n = 2
count = 0
while True:
next_n_lines = list(islice(file1,n))
print next_n_lines
count = count + 1
fileout = open(str(count)+ ".txt", "w+")
fileout.write(str(jcardtop))
fileout.write(str(next_n_lines))
fileout.close()
break
if not next_n_lines:
break
I do have the file printing as well to show what is in the variable next_n_lines.
*['\n', "randomtext' more junk here\n"]
I would like it instead to look like
randomtext' more junk here
Is this a limitatoin of the islice function? Or am I missing a portion of the syntax?
Thanks for your time!
Where you call str() or print, you want to ''.join(next_n_lines) instead:
print ''.join(next_n_lines)
and
fileout.write(''.join(next_n_lines))
You can store the flattened string in a variable if you don't want to call join twice.
Did you mean something like this?
f = open(userfile,"r")
start = 4
n_lines = 100
for line in f.readlines()[start:(start + n_lines)]:
print line
#do stuff with line
or maybe this rough, yet effective code:
f = open(userfile,"r")
start = 4
end = start + 100
count = start
while count != end:
for line in f.readlines()[count:(count + 2)]:
fileout = open(str(count)+ ".txt", "w+")
fileout.write(str(line))
fileout.close()
count = count + 2

Categories