0

I have 2 files:

  1. srv_to_snap.csv which lists servers each line like:
   srv1
   srv2
  1. rhev_srv_list_with_id.csv which has a list of servers with its ID each line like:
('srv1', '67876232-doiud987-834')
('srv2', '67876232-doiud9oo-123')
('srv3', '67876232-doi989oo-783')

I am trying to search the server name one by one from srv_to_snap.csv in rhev_srv_list_with_id.csv line by line and if a match is found, it will return only the id of the server.

I have tried the below code..

   with open('srv_to_snap.csv', 'r') as srv_list:
     for vm_name in srv_list:
       with open('rhev_srv_list_with_id.csv', 'rb') as f:
         for line in f:
           if vm_name in line:
             vm_id_tmp1 = str(line.split(" ")[1])
             vm_id = str(vm_id_tmp1.split("'")[1])
             print vm_id

This is not working as assignments can't be used in conditional statements. How do I work around this to get the IDs of all the vm_id's listed in srv_to_snap.csv?

I have tried re.search as well but it also didnt print the IDs... Requesting anyone to help me what I am missing here.

  • Why do you think this isn't working? What you have is perfectly legal. I think you misunderstand the rule about not using assignments in an `if` condition. You aren't doing that here, so the problem is something else. Please show the exact error message you get or the output from running your program and explain what it should be instead. – Code-Apprentice May 14 '20 at 15:04
  • Try opening the second file in text mode (not binary). It should work. – randomir May 14 '20 at 15:10
  • You can't use assignments in an *expression*. The body of an `if` statement is not an expression; it's a list of statements. What you *can't* do is something like `if (vm_name = "foo") in line` (though for certain use cases, there is an alternative introduced in Python 3.8.) – chepner May 14 '20 at 15:22

1 Answers1

0

You have two problems interfering with your condition check. Firstly you open the first file as a string and the second as binary and python cannot compare two objects of different types. Secondly, when you read a file line by line, you will have a newline character at the end. So for instance your code will search for srv1\n in the second file which it will not find.

Something like this should work if you know for sure that the newline character will always be \n:

with open('srv_to_snap.csv', 'r') as srv_list:
for vm_name in srv_list:
    with open('rhev_srv_list_with_id.csv', 'r') as f:
        for line in f:
            if vm_name.replace('\n', '') in line.replace('\n', ''):
                vm_id_tmp1 = str(line.split(" ")[1])
                vm_id = str(vm_id_tmp1.split("'")[1])
                print(vm_id)

Otherwise see How to read a file without newlines?

Donatien
  • 151
  • 6