`os.system` not able to find file created by `with open` and read by `with open`

  appdata, cmd, python, python-3.x, windows

In a Python3 program, os.system() is not able to find a file created in the APPDATA directory using with open, even after that same file can be successfully read by a subsequent with open.

QUESTION FOR THIS OP:

What specific syntax needs to be changed in the Python3 code below in order to successfully create a file in the APPDATA directory that can be found visually by users of the Windows Explorer API and also programmatically by the os.system() command below which is failing?

CURRENT CODE:

The following code is what we are currently trying:

print(os.getenv('APPDATA'))
terraformRC = os.path.join( os.getenv('APPDATA'), "terraform.rc")
print("terraformRC is: ", terraformRC)
print("About to write terraformRC. ")
try: 
  with open(terraformRC, 'w') as f:
    f.write('provider_installation {n')
    f.write('  filesystem_mirror {n')
    f.write('    path    = "' + providersPath + '"n')
    f.write('    include = ["*/*"]n')
    f.write('  }n')
    f.write('n')
    f.write('  direct {n')
    f.write('    exclude = ["*/*"]n')
    f.write('  }n')
    f.write('}n')
except (Exception) as e:
  print(e)

print("About to read the terraformRC we just wrote.  ")
with open(terraformRC, 'r') as lines:
  for line in lines:
    print(line)

print("About to disable settings for folder so that the terraformRC file can be unhidden.  ")
removeSettingsCmd = 'attrib -h -s ' + terraformRC
os.system(removeSettingsCmd)

CURRENT FAILED RESULTS:

The following output is printed by Windows CMD when we call the above Python3 code from Windows CMD.

C:pathtoAppDataRoaming
terraformRC is:  C:pathtoAppDataRoamingterraform.rc
About to write terraformRC.
About to read the terraformRC we just wrote.
provider_installation {
  filesystem_mirror {
    path    = "C:pathtodependenciesterraformproviders"
    include = ["*/*"]
  }
  direct {
    exclude = ["*/*"]
  }
}

About to disable settings for folder so that the terraformRC file can be unhidden.
File not found - C:pathtoAppDataRoamingterraform.rc

THE PROBLEM:

As you can see from the output above, Python seems to successfully find the APPDATA directory. Then Python seems to successfully write a terraformRC file to APPDATA. Then Python seems to successfully read the terraformRC file that it just seems to have written to APPDATA.

The problem is that the os.system(removeSettingsCmd) then fails with a message File not found - C:pathtoAppDataRoamingterraform.rc stating that it cannot find the terraformRC file at the correct location. And also, a human user is not able to view the terraformRC file when looking for it in APPDATA using Windows Explorer.

Source: Windows Questions

LEAVE A COMMENT