将迭代输出写入python中的文件 [英] Writing the iterative output into a file in python

查看:109
本文介绍了将迭代输出写入python中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将print语句的输出写入输出文件,而不是在控制台上打印它们。有没有简单的方法可以做到这一点,而不会影响我的打印语句中写的代码?

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?

代码: -

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()  


推荐答案

你需要在写入文件之前格式化你的字符串!!

You need to format your string before writing to file!!

print('\n,',"This is not a valid order record.")

output file.write('\n %s'%("This is not a valid order record.")

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()  

这篇关于将迭代输出写入python中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆