Python - Write Header Once - Loop isn't working properly - python

I am trying to write an "order file" with a Header and Detail Lines. I am successfully getting the order Header to write to file, but only one detail line seems to get written to the file.
for k, v in atlantic_billing.iteritems():
XHORNO = str(digits + counter)
XHCSNO = k
print XHCSNO
machines = v
line = 1
counter = counter + 1
header_written = False
try :
for machine in machines :
XDORNO = XHORNO
XDORSQ = line
line = line + 1
XDITD1 = ranpak_dict[machine]['MODEL']
XDITD2 = ranpak_dict[machine]['SN']
XDCAVC = ranpak_dict[machine]['TOTAL']
print XDORSQ, XDITD1, XDITD2, XDCAVC
if XDCAVC > 0 :
if header_written == False :
with open(XHORNO + ".txt", 'w') as order:
order.write("H01, " + XHORNO + ", " + XHCSNO + "\n")
order.write("D01," + str(XDORSQ) + ", " + ' EQPRANUSER, ' + XDITD1 + ", " + XDITD2 + ", " + XDCAVC + "\n")
else :
order.write("D01," + str(XDORSQ) + ", " + ' EQPRANUSER, ' + XDITD1 + ", " + XDITD2 + ", " + XDCAVC + "\n")
success.append(machine)
header_written = True
except KeyError, e:
issues.append(machine)

When opening the file, you should use the mode "A" else the file will be overwritten at each loop (again and again):
with open(XHORNO + ".txt", 'a') as order:
...
see https://docs.python.org/3/library/functions.html#open
An other option is to take the withblock over the for block.

You need to open the file only once and not inside the loop
for k, v in atlantic_billing.iteritems():
XHORNO = str(digits + counter)
with open(XHORNO + ".txt", 'w') as order: # <--- here you go
XHCSNO = k
print XHCSNO
machines = v
line = 1
counter = counter + 1
header_written = False
try :
for machine in machines :
XDORNO = XHORNO
XDORSQ = line
line = line + 1
XDITD1 = ranpak_dict[machine]['MODEL']
XDITD2 = ranpak_dict[machine]['SN']
XDCAVC = ranpak_dict[machine]['TOTAL']
print XDORSQ, XDITD1, XDITD2, XDCAVC
if XDCAVC > 0 :
if header_written == False :
order.write("H01, " + XHORNO + ", " + XHCSNO + "\n")
order.write("D01," + str(XDORSQ) + ", " + ' EQPRANUSER, ' + XDITD1 + ", " + XDITD2 + ", " + XDCAVC + "\n")
else :
order.write("D01," + str(XDORSQ) + ", " + ' EQPRANUSER, ' + XDITD1 + ", " + XDITD2 + ", " + XDCAVC + "\n")
success.append(machine)
header_written = True
except KeyError, e:
issues.append(machine)

Try this:
for k, v in atlantic_billing.iteritems():
XHORNO = str(digits + counter)
XHCSNO = k
print XHCSNO
machines = v
line = 1
counter = counter + 1
header_written = False
try :
for machine in machines :
XDORNO = XHORNO
XDORSQ = line
line = line + 1
XDITD1 = ranpak_dict[machine]['MODEL']
XDITD2 = ranpak_dict[machine]['SN']
XDCAVC = ranpak_dict[machine]['TOTAL']
print XDORSQ, XDITD1, XDITD2, XDCAVC
if XDCAVC > 0 :
with open(XHORNO + ".txt", 'a') as order:
if header_written == False :
order.write("H01, " + XHORNO + ", " + XHCSNO + "\n")
order.write("D01," + str(XDORSQ) + ", " + ' EQPRANUSER, ' + XDITD1 + ", " + XDITD2 + ", " + XDCAVC + "\n")
header_written = True
else :
order.write("D01," + str(XDORSQ) + ", " + ' EQPRANUSER, ' + XDITD1 + ", " + XDITD2 + ", " + XDCAVC + "\n")
success.append(machine)
except KeyError, e:
issues.append(machine)

Related

Python adds a double entry at the end of output file

This is my code to create a hashtag file. The issue is it does not put the # for the first hashtag and at he end it puts a double hashtag like below.
passiveincome, #onlinemarketing, #wahmlife, #cash, #entrepreneurlifestyle, #makemoneyonline, #makemoneyfast, #entrepreneurlifestyle, #mlm, #mlm
How do I get the code to remove the double output and put the # at the beginning?
import random, os, sys
basepath = os.path.dirname(sys.argv[0]) + "/"
outputpath = "C:/Users/matth/OneDrive/Desktop/Create hashtags/"
paragraphsmin = 9
paragraphsmax = 9
sentencemin = 1
sentencemax = 1
keywords = []
for line in open(basepath + "/base.txt", "r"):
keywords.append(line.replace("\n",""))
keywordlist = []
keyword = open(basepath + "/text-original.txt", "r")
for line in keyword:
keywordlist.append(line.replace("\n", "\n"))
def type(name):
value = name[random.randint(0,len(name)-1)]
return value
"""
def xyz(num):
s1 = '' + type(keywordlist).strip()
return eval('s' + str(num))
"""
def s1():
return '' + type(keywordlist).strip()
def randomSentence():
sent = eval("s" + str(random.randint(1,1)) + "()")
return sent
for keyword in keywords:
outputfile = open(outputpath + keyword.replace(" ", " ") + ".txt", "w")
outputfile.write('')
for p in range(1,random.randint(paragraphsmin,paragraphsmax) + 1):
outputfile.write('')
for s in range(1,random.randint(sentencemin,sentencemax) + 1):
sentence = randomSentence()
if str(sentence)[0] == "\"":
outputfile.write("" + str(sentence)[0] + str(sentence)[1] + str(sentence)[2:] + " ")
else:
outputfile.write("" + str(sentence)[0] + str(sentence)[1:] + ", #")
outputfile.write('')
outputfile.write(sentence.replace("", "") + "")
outputfile.close()
Try replacing
outputfile.write("" + str(sentence)[0] + str(sentence)[1:] + ", #")
with
outputfile.write("#" + str(sentence)[0] + str(sentence)[1:] + ", ")

TypeError: mat data type = 19 is not supported

I'm writing a code that creates a random image. The way I do this is by taking a LOT of different random values and creating a file. The file will than be read and shown via OpenCV. See the example.
def R_Write():
if os.path.exists("draw_data.pgi"):
os.remove("draw_data.pgi")
d_data = open("draw_data.pgi", "w")
d_data.write("[[[")
d_data.write(d[1] + " " + d[2] + " " + d[3]+ "]" + "\n")
d_data.write(" " + "[" + d[4] + " " + d[5] + " " + d[6] + "]" + "\n")
d_data.write(" " + "[" + d[7] + " " + d[8] + " " + d[9] + "]" + "\n")
d_data.write(" " + "..." + "\n")
d_data.write(" " + "[" + d[10] + " " + d[11] + " " + d[12] + "]" + "\n")
d_data.write(" " + "[" + d[13] + " " + d[14] + " " + d[15] + "]" + "\n")
d_data.write(" " + "[" + d[16] + " " + d[17] + " " + d[18] + "]]" + "\n")
d_data.write("\n")
d_data.write(" " + "[[" + d[19] + " " + d[20] + " " + d[21] + "]" + "\n")
d_data.write(" " + "[" + d[22] + " " + d[23] + " " + d[24] + "]" + "\n")
d_data.write(" " + "[" + d[25] + " " + d[26] + " " + d[27] + "]" + "\n")
d_data.write(" " + "..." + "\n")
d_data.write(" " + "[" + d[28] + " " + d[29] + " " + d[30] + "]" + "\n")
d_data.write(" " + "[" + d[31] + " " + d[32] + " " + d[33] + "]" + "\n")
d_data.write(" " + "[" + d[34] + " " + d[35] + " " + d[36] + "]]" + "\n")
d_data.write("\n")
d_data.write(" " + "[[" + d[37] + " " + d[38] + " " + d[39] + "]" + "\n")
d_data.write(" " + "[" + d[40] + " " + d[41] + " " + d[42] + "]" + "\n")
d_data.write(" " + "[" + d[43] + " " + d[44] + " " + d[45] + "]" + "\n")
d_data.write(" " + "..." + "\n")
d_data.write(" " + "[" + d[46] + " " + d[47] + " " + d[48] + "]" + "\n")
d_data.write(" " + "[" + d[49] + " " + d[50] + " " + d[51] + "]" + "\n")
d_data.write(" " + "[" + d[52] + " " + d[53] + " " + d[54] + "]]" + "\n")
d_data.write("\n")
d_data.write(" " + "..." + "\n")
d_data.write("\n")
d_data.write(" " + "[[" + d[37] + " " + d[38] + " " + d[39] + "]" + "\n")
d_data.write(" " + "[" + d[40] + " " + d[41] + " " + d[42] + "]" + "\n")
d_data.write(" " + "[" + d[43] + " " + d[44] + " " + d[45] + "]" + "\n")
d_data.write(" " + "..." + "\n")
d_data.write(" " + "[" + d[46] + " " + d[47] + " " + d[48] + "]" + "\n")
d_data.write(" " + "[" + d[49] + " " + d[50] + " " + d[51] + "]" + "\n")
d_data.write(" " + "[" + d[52] + " " + d[53] + " " + d[54] + "]]" + "\n")
d_data.write("\n")
d_data.write(" " + "[[" + d[55] + " " + d[56] + " " + d[57] + "]" + "\n")
d_data.write(" " + "[" + d[58] + " " + d[59] + " " + d[60] + "]" + "\n")
d_data.write(" " + "[" + d[61] + " " + d[62] + " " + d[63] + "]" + "\n")
d_data.write(" " + "..." + "\n")
d_data.write(" " + "[" + d[64] + " " + d[65] + " " + d[66] + "]" + "\n")
d_data.write(" " + "[" + d[67] + " " + d[68] + " " + d[69] + "]" + "\n")
d_data.write(" " + "[" + d[70] + " " + d[71] + " " + d[72] + "]]" + "\n")
d_data.write("\n")
d_data.write(" " + "[[" + d[73] + " " + d[74] + " " + d[75] + "]" + "\n")
d_data.write(" " + "[" + d[76] + " " + d[77] + " " + d[78] + "]" + "\n")
d_data.write(" " + "[" + d[79] + " " + d[80] + " " + d[81] + "]" + "\n")
d_data.write(" " + "..." + "\n")
d_data.write(" " + "[" + d[82] + " " + d[83] + " " + d[84] + "]" + "\n")
d_data.write(" " + "[" + d[85] + " " + d[86] + " " + d[87] + "]" + "\n")
d_data.write(" " + "[" + d[88] + " " + d[89] + " " + d[90] + "]]]")
d_data.close()
d_data = open("draw_data.pgi", "r").read()
print(d_data)
Draw(d_data)
def Draw(data):
cv2.imshow("Random_Pixels", np.array(data))
But then the error occurs TypeError: mat data type = 19 is not supported. How do I convert it to a other type or how do I resolve the problem?
I already tried a couple of things like,
data_2 = np.int16(data) # convert to signed 16 bit integer to allow overflow
data_2 = scale_factor*data_2 # apply scale factor
data_2 = clip(data_2, 0, 255) # force all values to be between 0 and 255
# after clip img2 is effectively unsigned 8 bit, but make it explicit:
data_2 = np.uint8(data_2)
please help me? I am really motivated for this project and I would like to continue it, but I can't without your help.

How to put together datas into a file?

I would like to collect different type of datas into a file. Here is a part of the code.
val = str(float(data[-1]))
val_dB = float(val)
val_dB = math.log(val_dB, 10) * 10
myfile = open('../../../MLI_values/mli_value.txt', 'a')
myfile.write(date_ID + " " + val + val_dB + "\n")
myfile.close()
But it gives back an error:
myfile.write(date_ID + " " + val + val_dB + "\n")
TypeError: cannot concatenate 'str' and 'float' objects
How can I solve it to put them together? (into columns) into a file?
Change:
myfile.write(date_ID + " " + val + val_dB + "\n")
to:
myfile.write(date_ID + " " + val + " " + str(val_dB) + "\n")

How to select specific data from CSV files and display all the data in that row

I'm trying to make a code that shows all the details of specific students. The code takes an input of gender and their class and then shows all their data. For example, if I input "Male" and "10A", I want the code to give me all the data from the students who are male and in class 10A. All their information is stored in a CSV file (called details). My code so far is:
file = open("details.csv","rt")
gender_input = input("Input gender of students")
class_input = input("Input class of students")
for line in file:
details_of_gender = line.split(",")
details_of_class = line.split(",")
gender = str(details_of_gender[7])
class1 = str(details_of_class[8])
if gender == "Male":
if class1 == "10A":
print(details[0] + " " + details[1] + " " + details[2] + " " + details[3] + " " + details[4] + " " + details[5])
if class1 == "10B":
print(details[0] + " " + details[1] + " " + details[2] + " " + details[3] + " " + details[4] + " " + details[5])
if gender == "Female":
if class1 == "10A":
print(details[0] + " " + details[1] + " " + details[2] + " " + details[3] + " " + details[4] + " " + details[5])
if class1 == "10B":
print(details[0] + " " + details[1] + " " + details[2] + " " + details[3] + " " + details[4] + " " + details[5])
Assuming that your program isn't working just because you're using a variable details that you haven't defined before, here's a better way of doing this:
import csv
with open("details.csv", newline="") as infile:
reader = csv.reader(infile) # use the csv module to read a CSV file!
for row in reader:
gender = row[7]
class = row[8]
if gender in ("Male", "Female") and class in ("10A", "10B"):
print(" ".join(row[:6])) # join elements 0-5 with spaces

Timestamp into output filename

I would like to insert the timestamp into an output filename of a python script, for example: 20011231_230159_md5_filelist.csv
I am having trouble inserting the code.
This is the end of the script whose output filename needs to have a timestamp:
try:
my_last_data = get_md5(file_full_path) + ", " + get_last_write_time(file_full_path) + ", " + get_size(
file_full_path) + ", " + file_full_path + "\n"
with open("md5_filelist.csv", "a") as my_save_file:
my_save_file.write(my_last_data)
print(str(file_full_path) + " ||| Done")
except:
print("Error On " + str(file_full_path))
This is the timestamping code I am battling with (although not sure if it is the best line for the purpose):
timestr = time.strftime("%Y%m%d_%H%M%S")
I tried inserting in various ways, does not work. Any hints?
Thank you to #pm-2ring (see comments), the solution:
timestr = time.strftime("%Y%m%d_%H%M%S")
(timestr + "_md5_filelist.csv", "a")
in the script:
try:
timestr = time.strftime("%Y%m%d_%H%M%S")
my_last_data = get_md5(file_full_path) + ", " + get_last_write_time(file_full_path) + ", " + get_size(
file_full_path) + ", " + file_full_path + "\n"
with open(timestr + "_md5_filelist.csv", "a") as my_save_file:
my_save_file.write(my_last_data)
print(str(file_full_path) + " ||| Done")
except:
print("Error On " + str(file_full_path))
This is all you need.
try:
my_last_data = get_md5(file_full_path) + ", " + get_last_write_time(file_full_path) + ", " + get_size(
file_full_path) + ", " + file_full_path + "\n"
with open("{}md5_filelist.csv".format(timestr), "a") as my_save_file:
my_save_file.write(my_last_data)
print(str(file_full_path) + " ||| Done")
except:
print("Error On " + str(file_full_path))
You were not using timestr anywhere in you code.

Categories