在运行在Windows 10中的Python3程序中,os.system()
无法找到使用with open
在APPDATA
目录中创建的文件,即使该文件可以被后续的with open
成功读取。
关于这个OP的问题:
在下面的Python3代码中需要更改哪些特定的语法才能成功地在
APPDATA
目录中创建一个文件,该文件可以由Windows10Explorer UI的用户直观地找到,也可以通过下面的os.system()
命令以编程方式找到,这是失败的?
当前代码:
下面的代码是我们目前正在尝试的:
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)
当前失败结果:
当我们从Windows调用上述Python3代码时,Windows会打印以下输出。
C:\path\to\AppData\Roaming
terraformRC is: C:\path\to\AppData\Roaming\terraform.rc
About to write terraformRC.
About to read the terraformRC we just wrote.
provider_installation {
filesystem_mirror {
path = "C:\path\to\dependencies\terraform\providers"
include = ["*/*"]
}
direct {
exclude = ["*/*"]
}
}
About to disable settings for folder so that the terraformRC file can be unhidden.
File not found - C:\path\to\AppData\Roaming\terraform.rc
问题:
从上面的输出可以看出,Python似乎成功地找到了APPDATA
目录。然后Python似乎成功地将terraformRC文件写入APPDATA
。然后Python似乎成功地读取了它似乎已经写入APPDATA
的APPDATA
文件。
问题是,os.system(removeSettingsCmd)
随后失败了,其中有一条消息File not found - C:\path\to\AppData\Roaming\terraform.rc
声明它无法在正确的位置找到terraformRC文件。而且,在使用Windows在terraformRC中查找APPDATA
文件时,人类用户无法查看它。
发布于 2021-08-11 21:58:46
您似乎已经从Microsoft安装了Python。存储应用程序是通用Windows平台()应用程序,并将AppData存储在每个用户的基础上重定向到本地应用程序(如attrib
)所不知道的特定用户的特定区域。有关更多信息,请参见UWP -存储和检索设置和其他应用程序数据。
我建议卸载Python的UWP版本,并从python.org安装一个正式的本机二进制文件,这将如您所期望的那样工作。
https://stackoverflow.com/questions/68719108
复制