将迭代输出写入python中的文件

时间:2017-04-05 14:11:50

标签: python python-3.x if-statement

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

代码: -

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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

如果您不想更改任何代码,可以将打印功能更改为附加到文件中:

def print(*args):
    with open("output1.txt", "a") as outputfile:
        outputfile.write(" ".join(str(arg) for arg in args) + "\n")

但最好是创建一个这样的新函数:

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