英文:
I am trying to save the output of linux server command to excel file using python
问题
在下面的代码中,我正在登录多个服务器并执行命令cat /etc/passwd
,然后尝试将该命令的输出保存到单独的Excel文件中。然而,我得到了正确的输出,但无法将其保存到Excel文件中。在保存到Excel时出现以下错误:
import xlsxwriter
cred = open("creds.csv", "r")
for i in cred.readlines():
# 从cat /etc/passwd获取用户
users = ...
users = "".join(users)
print(users)
row = 1
col = 0
workbook = xlsxwriter.Workbook("%s.xlsx" % ls[3], "w")
worksheet = workbook.add_worksheet()
for name in (users):
worksheet.write(row, col, name)
#worksheet.write(row, col + 1, score)
row += 1
cred.close()
错误的原因是在创建xlsxwriter.Workbook
对象时传递了错误的参数。应该像下面这样创建工作簿对象:
workbook = xlsxwriter.Workbook("%s.xlsx" % ls[3])
只需删除"w"
参数,这样就能够创建Excel工作簿而不会引发AttributeError
。
英文:
I am trying to login multiple linux server and execute some commamnd and save the output of that command into new Excel file for each server.
In the below code I am loggin multiple servers and excecuting command cat /etc/passwd
and trying to save this output in a separate Excel file.
However I got the correct output but I am not able to save it in to Excel file.
import xlsxwriter
cred = open("creds.csv","r")
for i in cred.readlines():
# Get users from cat /etc/passwd
users = ...
users ="".join(users)
print(users)
row = 1
col = 0
workbook = xlsxwriter.Workbook("%s.xlsx"%ls[3],"w")
worksheet = workbook.add_worksheet()
for name in (users):
worksheet.write(row, col, name)
#worksheet.write(row, col + 1, score)
row += 1
cred.close()
I am getting desired out from linux server but not able to save it to excel file.
But while saving to excel getting below error
Traceback (most recent call last):
File "c:\Users\mukes\OneDrive\Documents\Script\obsolute_path", line 27, in <module>
workbook = xlsxwriter.Workbook("%s.xlsx"%ls[3],"w")
File "C:\Users\mukes\AppData\Local\Programs\Python\Python310\lib\site-packages\xlsxwriter\workbook.py", line 75, in __init__
self.tmpdir = options.get('tmpdir', None)
AttributeError: 'str' object has no attribute 'get'
PS C:\Users\mukes\OneDrive\Documents\Script>
答案1
得分: 1
通过一次Google搜索,您将找到xlsxwriter
的文档。您将选项传递为字符串。这就是代码抱怨字符串的原因。文档中说Workbook
需要一个字典。
在我提供的文档中,您将看到无需指定要以写入模式打开工作簿。该库被称为“writer”,这是它的默认行为。
英文:
With just one Google search you will find the documentation of xlsxwriter
.You are passing your options as a string. That's why the the code complains about a string. The documentation says that Workbook
expects a dictionary.
In the documentation I linked you will see there is no need to specify you want to open your Workbook in writing mode. The library is called writer, that's its behavior by default.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论