I am not using Python on a daily basis and I have one error which you might help me with. I have the following code:
import xlrd
import xlwt
import xlsxwriter
string1="Last password change"
string2="Password expires"
string3="Password inactive"
string4="Account expires"
string5="Minimum number of days between password change"
string6="Maximum number of days between password change"
string7="Number of days of warning before password expires"
workbook=xlsxwriter.Workbook('/media/sf_vboxshared/sample.xlsx')
worksheet1=workbook.add_worksheet('Sheet1')
with open('sample.txt','r') as dump:
for line in dump:
if string1 in line:
tail1=line.split(string1)[1]
tail1=tail1.strip()
tail1=tail1.lstrip(":")
for num, line in enumerate(dump, 1):
if string1 in line:
worksheet1.write(num,1,string1)
worksheet1.write(num,2,tail1)
with open('sample.txt', 'r') as dump2:
for line2 in dump2:
if string2 in line2:
tail2=line2.split(string2)[1]
tail2=tail2.strip()
tail2=tail2.lstrip(":")
for num, line2 in enumerate(dump2, 1):
if string2 in line2:
worksheet1.write(num,1,string2)
worksheet1.write(num,2,tail2)
workbook.close()
The input looks like this(sample.txt):
rick
Last password change : Feb 26, 2018
Password expires : never
Password inactive : never
Account expires : never
Minimum number of days between password change : 0
Maximum number of days between password change : 99999
Number of days of warning before password expires : 7
john
Last password change : Feb 26, 2018
Password expires : never
Password inactive : never
Account expires : never
Minimum number of days between password change : 0
Maximum number of days between password change : 99999
Number of days of warning before password expires : 7
frank
Last password change : Feb 26, 2018
Password expires : never
Password inactive : never
Account expires : never
Minimum number of days between password change : 0
Maximum number of days between password change : 99999
Number of days of warning before password expires : 7
romeo
Last password change : Feb 26, 2018
Password expires : never
Password inactive : never
Account expires : never
Minimum number of days between password change : 0
Maximum number of days between password change : 99999
Number of days of warning before password expires : 7
The idea of this code is that I want to export the exact tabs into the Excel from the sample.txt file, but formatted properly. Basically, the : delimitates the columns. When you run this code, the second "with" is going to overwrite the info. Can someone explain me why is it this behavior and how can be fixed?
Many thanks in advance, Romain.
with open('sample.txt', 'r') as?