簡體   English   中英

Python腳本錯誤-將輸出保存到文本文件

[英]Python script error- Save output to a text file

我正在嘗試將輸出保存到文件,並且縮進沒問題。.但我一直收到此錯誤,請參見以下內容:

這是下面的錯誤:

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

請幫助此代碼

使用str方法將輸出變量轉換為字符串對象

例如:

with open(filename, 'w') as file:
    file.write(str(output))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM