问题
I am trying to write the output of my print statements into an output file instead of printing them at console. Is there any simple way to do that without affecting the code written in my print statements?
Code :-
outputfile = open('output1.txt','w')
outputfile.write("Order_id Order_date User_id Avg_Item_Price Start_page_url Error_msg")
for i in inputm[1:]:
if '::' in i[0] or ':' not in i[0]:
print('\n',"This is not a valid order record.")
else:
print('\n',i[0].split(':')[0]
,str(datetime.strptime(i[0].split(':')[1],'%Y%m%d'))[:10]
,i[1]
,round(sum( float(v) if v else 0.0 for v in i[2:6])/4,2)
,i[6] if Counter(i[6][0:23]) == Counter("http://www.google.com") else ' '
,'Valid URL' if Counter(i[6][0:23]) == Counter("http://www.google.com") else 'Invalid URL'
)
outputfile.close()
回答1:
You need to format your string before writing to file!!
print('\n,',"This is not a valid order record.")
to
output file.write('\n %s'%("This is not a valid order record.")
that is
outputfile = open('output1.txt','w')
outputfile.write("Order_id Order_date User_id Avg_Item_Price Start_page_url Error_msg")
for i in inputm[1:]:
if '::' in i[0] or ':' not in i[0]:
outputfile.write('\n %s'%("This is not a valid order record."))
else:
outputfile.write('\n%s %s %s %f %s %s'%(i[0].split(':')[0]
,str(datetime.strptime(i[0].split(':')[1],'%Y%m%d'))[:10]
,str(i[1])
,round(sum( float(v) if v else 0.0 for v in i[2:6])/4,2)
,i[6] if Counter(i[6][0:23]) == Counter("http://www.google.com") else ' '
,'Valid URL' if Counter(i[6][0:23]) == Counter("http://www.google.com") else 'Invalid URL'))
outputfile.close()
回答2:
If you don't want to change any of your code, you could change the print function to append to the file instead:
def print(*args):
with open("output1.txt", "a") as outputfile:
outputfile.write(" ".join(str(arg) for arg in args) + "\n")
But it would be better to create a new function like this:
def write_to_file(*args):
with open("output1.txt", "a") as outputfile:
outputfile.write(" ".join(str(arg) for arg in args) + "\n")
write_to_file("Order_id Order_date User_id Avg_Item_Price Start_page_url Error_msg")
for i in inputm[1:]:
if '::' in i[0] or ':' not in i[0]:
write_to_file('\n',"This is not a valid order record.")
else:
write_to_file('\n',i[0].split(':')[0]
,str(datetime.strptime(i[0].split(':')[1],'%Y%m%d'))[:10]
,i[1]
,round(sum( float(v) if v else 0.0 for v in i[2:6])/4,2)
,i[6] if Counter(i[6][0:23]) == Counter("http://www.google.com") else ' '
,'Valid URL' if Counter(i[6][0:23]) == Counter("http://www.google.com") else 'Invalid URL'
)
outputfile.close()
来源:https://stackoverflow.com/questions/43233717/writing-the-iterative-output-into-a-file-in-python