-1

I need to pass an argument that has to read a file as well as a string in the python function. Here, it works fine when I pass a filename as variable, but the elif block doesn't work here which has to read a string. Please help

     def test_save(self, test_data):
          if Path(test_data).is_file():
                with open(test_data, 'r') as f:
                    result= f.read()
          elif type(test_data) is str:
                result= test_data
          data = {
                "president": {
                 "details": result
                             }
     test_data_String_value = "<note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>"            } 
     test_save(test_data_String_value)
     

              


   

     
TechG
  • 29
  • 3
  • Please supply the expected [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) (MRE). We should be able to copy and paste a contiguous block of your code, execute that file, and reproduce your problem along with tracing output for the problem points. This lets us test our suggestions against your test data and desired output. "Doesn't work" is not a problem specification. – Prune Mar 29 '21 at 20:57
  • See [How to check if type of a variable is string?](https://stackoverflow.com/questions/4843173/how-to-check-if-type-of-a-variable-is-string) – Gino Mempin Mar 29 '21 at 23:57

1 Answers1

0

Try:

  • replacing type(test_data) is str with isinstance(test_data, str)
  • adding a return data after the if / elif block

With the string you provide, test_save raises an OSError, which you might want to catch with a try / except statement.

Laurent
  • 12,287
  • 7
  • 21
  • 37