关于python:AttributeError:’tuple’对象在写入文件时没有属性’write’错误

AttributeError: 'tuple' object has no attribute 'write' error while writing into a file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from netmiko import ConnectHandler      
from textfsm import *

cisco_device = { 'device_type' : 'cisco_ios', 'ip' : 'x.x.x.x', 'username':'gtomy200', 'password':'xxxxx'}
net_connect = ConnectHandler(**cisco_device)

fo=("testme.txt" , 'w')

output = net_connect.send_command("show int brief")

re_table = TextFSM(open('xr_show_int_br','r'))    

data = re_table.ParseText(output)

print (output)

for s in re_table.header:

          fo.write("%s;" %s)

fo.write("
"
)

for row in data:
        print (row)
        for s in row:

                fo.write("%s" %s)
                fo.write("
"
)

fo.close()

关于以下错误,有人能帮忙吗?

1
2
3
4
Traceback (most recent call last):
  File"/Users/gtomy200/Desktop/Py/test.py", line 20, in
    fo.write("%s;" %s)
AttributeError: 'tuple' object has no attribute 'write'


fo是一个元组,使用with open()进行文件操作。更安全更容易。

1
2
3
with open ("myfile.txt","w") as ff:
    ff.write("string") #you can't use anything but strings in here,
                       #so convert your variables to string

您要确保您的open文件:

1
2
fo = open("testme.txt" , 'w')
#    ^^^^

事实上,你想写两个元组:

1
2
fo = ("testme.txt", 'w')
#    ^ no open

这不管用。