Skip to content Skip to sidebar Skip to footer

Writing The Iterative Output Into A File In Python

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 writte

Solution 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':'notin 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 else0.0for 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()  

Solution 2:

If you don't want to change any of your code, you could change the print function to append to the file instead:

defprint(*args):
    withopen("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()  

Post a Comment for "Writing The Iterative Output Into A File In Python"