0

I'm trying to load configurations from an external file (config.txt). The file contains info about directories on my drive. I have written a method for reading one line of the config.txt and return its value. A second method checks the existence of a directory. The first call of latter method always results into a False, even if given directory exists.

I tried different directories, even the same directory in both lines. For the first call I always get a "False". The second call results into the right answer. If the method is called from the terminal with any directory I get the right result.

import os    

def _load_config(setting_line, setting_print):
     temp_file = open("config.txt", "r")
     temp_setting = temp_file.readlines()[setting_line]
     temp_file.close()
     print(setting_print,temp_setting)
     return temp_setting

 def _Check_Folder_Exists(temp_path):
    if os.path.exists(temp_path):
        print("dir found")
    else:
        print("dir NOT found")

dir_A = _load_config(0, "dir A:")
_Check_Folder_Exists(dir_A)

dir_B = _load_config(1, "dir B:")
_Check_Folder_Exists(dir_B)

the config.txt looks like:

C:\A
C:\B

Both directories exist and are accessible.

Results are always:

dir A: C:\A

dir NOT found
dir B: C:\B
dir found

Also: I can't see why there is an empty line after the first one.

herrwolken
  • 389
  • 1
  • 4
  • 12

1 Answers1

0

The two issues are related. It's because when you use readlines(), you get the whole line including the line break; so the value of dir_A is actually C:\A\n.

Use strip:

temp_setting = temp_file.readlines()[setting_line].strip()
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895