Python脚本错误 - 将输出保存到文本文件

时间:2018-01-19 16:11:13

标签: python file text

我正在尝试将输出保存到文件中并且缩进没有问题..但我一直收到此错误,请参阅下文:

这是以下错误:

Traceback (most recent call last):
  File "command.py", line 36, in <module>
    file.write(output)
TypeError: expected a character buffer object

有人可以查看我下面的代码,看看我做错了什么。我是python的新手,所以任何帮助都会受到赞赏。

#Importing the necessary module. help
 from trigger.cmds import Commando

#Asking the user for input.
 devices = raw_input('\nEnter devices separated by comma: ')
 commands = raw_input('\nEnter commands separated by comma: ')

#Splitting the devices/commands entered by the user.
 devices_list = devices.split(',')
 commands_list = commands.split(',')

#Running all given commands on all given devices. 
 cmd = Commando(devices = devices_list, commands = commands_list)

#Executing all the work.
cmd.run()

#Capturing the results
 output = cmd.results
#print output

#Asking the user if they want to print to screen or save to file.
 user_option = raw_input('Type "p" to print to screen or "s" to save to file: ')

 if user_option == 'p':
        print output

 elif user_option == "s":
        filename = raw_input('Please name your file. Example: /home/ubuntu/bgp.txt: ')

        #Print the output to file.
        with open(filename, 'w') as file:
                file.write(output)

        print "Done...Check out %s to see the results." % filename

#End of Program

请帮助解释此代码

1 个答案:

答案 0 :(得分:0)

使用 str 方法

将输出变量转换为字符串对象

EX:

with open(filename, 'w') as file:
    file.write(str(output))
相关问题