I am writing a code, where I am generating some rules. Below are the last few lines of my code:
for _,i in enumerate(range(no_of_label 1)):
if _ in temp_key:
rule_pro.append(temp_lab[_])
elif _ == no_of_label:
rule_pro.append(class_)
else:
rule_pro.append("*")
print(*rule_pro, sep = ",")
Now in between the code I am generating 3-4 outputs in the stdout as well. But I need to write this rule_pro
into a file say, Outputfile
. Whenever I am trying to copy this thing from stdout to that file, everything that is in stdout is getting copied but I only need to bring that rule_pro
inside a file. How can I do that? Please help!
Edit_1 :
with open('Output_rule_c45_rise_format', 'w') as file_handler:
file_handler.write(str(rule_pro))
This is working but I am not getting my desired format, which I was getting in stdout
using print(*rule_pro, sep = ",")
.
The stdout
output was like:
*,*,1,*,0
*,*,2,2,1
*,*,*,3,1
*,*,*,4,2
*,*,3,*,2
But modifying the code, in that outputfile I am getting like :
['*', '*', '1', '*', '0']['*', '*', '2', '2', '1']['*', '*', '*', '3', '1']['*', '*', '*', '4', '2']['*', '*', '3', '*', '2']
But I don't need these 3rd brackets and I need to print them in separate lines. What changes should I need to make?
Edit_2:
Now I am doing :
for rule in rule_pro:
#rule_line = ','.join(map(str, rule))
#rule_line = "\n".join(map(str, rule))
rule_line = "\n".join(map(str, rule)) '\n'
file_handler.write(rule_line)
But this is giving the output as:
*
*
1
*
0
*
*
2
2
1
*
*
*
3
1
*
*
*
4
2
*
*
3
*
2
CodePudding user response:
After Edit 1.
It seems that you are writing a string representation of a list into a file. You should first try to create a string out of the list.
The code below should help you convert this. It iterates trough the list and obtaining every item. In this case it seems you have a list with lists and thus your item is a list. After this, a string is joined/created by using every item in rule (which is a list) and then saves it in a variable. The rule_line is a string and can be written to the file. A newline is added so it gets on the next line in the file.
with open('Output_rule_c45_rise_format', 'w') as file_handler:
for rule in rule_pro:
rule_line = ','.join(map(str, rule)) '\n'
file_handler.write(rule_line)
This should work assuming that rule_pro is a list of lists.
CodePudding user response:
check docs: Python File Handling:https://www.w3schools.com/python/python_file_handling.asp
Python File Open:https://www.w3schools.com/python/python_file_open.asp
Python File Write:https://www.w3schools.com/python/python_file_write.asp
Python File Delete:https://www.w3schools.com/python/python_file_remove.asp