I am writing script to add string A to server1, B to server2 and C to server3.
As per the below script, incorrectly it writes C to all servers.Pls could share insights.
Python Script:
command = []
command.append('server ')
command.append('server1 ')
command.append('server3')
output = ['A','B','C']
for i in command:
file = open(i '_output.txt', 'w')
file.close()
for j in output:
for i in command:
file = open(i '_output.txt', 'w')
file.write(j)
file.close()
Expected output:
server_output.txt has text "A"
server1_output.txt has text "B"
server2_output.txt has text "C"
CodePudding user response:
you are doing the looping wrong..
think about the last iteration of j
variable in the loop
it points to c
then inner loop goes through each file and and writes c
to them
to fix it you need only one loop
for i in range(len(command)):
file = open(command[i] '_output.txt', 'w')
file.write(output[i])
file.close()
CodePudding user response:
Follow just Four simple steps and get the solutions.
Step 1 - Opening a text file. df=open('text file','w') ... Step 2 - Adding a test line in the file. df.write('We will be seeing an interated printing of numbers between 0 to 10\n') ... Step 3 - Writing a for loop over the file. for i in range(0,11): df.write(str(i)) df.write('\n') ...
Step 4 - Closing the text file. df.close()