类似于打印的函数,用于将字符串写入文本文件

std*_*err 2 python arguments function

我想在Python中编写一个函数来获取参数print,但不是将字符串打印到stdout,我想将格式化的字符串写入文本文件.

我如何定义这样的函数参数的参数来接受字符串格式化,我想知道吗?

我正在寻找可以取代的东西

print "Test"
Run Code Online (Sandbox Code Playgroud)

MyLog "Test"
Run Code Online (Sandbox Code Playgroud)

但是也应该支持%rguments.到目前为止,我只想出这个:

def logger(txt):    
fh = open (LOGFILE, "a") #Get handle in append mode
fh.write(txt)
fh.close()
print txt
return True 
Run Code Online (Sandbox Code Playgroud)

这适用于一个简单的字符串,但我认为它不会采用%参数,也不会像logger"TEST"那样调用它

Sam*_*ann 5

您可以使用"print chevron"语句执行您想要的操作:

with open('filename.txt', 'w') as f:
  print >> f, my_object
Run Code Online (Sandbox Code Playgroud)

请参阅print语句的文档.

当然,使用print()Martijn Pieters 建议的功能可能是更好的做法.

更新

如果我改变你的logger函数使用print chevron语法,我得到这个:

def logger(txt):    
  fh = open (LOGFILE, "a") #Get handle in append mode
  fh.write(txt)
  fh.close()
  print >>fh, txt
  return True 
Run Code Online (Sandbox Code Playgroud)

如果您将此功能称为:

now, duration = 4.0, 2.0
logger("User request at %f time took %f seconds." % (now, duration))
Run Code Online (Sandbox Code Playgroud)

您的日志文件中会有一行如下所示:

User request at 4.0 time took 2.0 seconds.
Run Code Online (Sandbox Code Playgroud)

所以你可以将它与%格式化一起使用(虽然你真的应该看看新式格式化),但是你不能像下面那样调用它:

logger "User request at %f time took %f seconds." % (now, duration)
Run Code Online (Sandbox Code Playgroud)

那是因为print是一个简单的语句,它是一个语言级别的构造,你不能将它们添加到Python中.