我正在尝试通过已存在的路径目录C:\ ProgramData \ myFolder \ doc.txt在python中获取路径以打开和写入文本文档,无需创建它,但使其在用户上使用python可执行文件电脑。例如,如果这样我在那里有文件夹:
mypath = os.path.join(os.getenv('programdata'), 'myFolder')
然后如果我想写:
data = open (r'C:\ProgramData\myFolder\doc.txt', 'w')
或打开它:
with open(r'C:\ProgramData\myFolder\doc.txt') as my_file:
不确定它是否正确:
programPath = os.path.dirname(os.path.abspath(__file__))
dataPath = os.path.join(programPath, r'C:\ProgramData\myFolder\doc.txt')
并以此为例使用它:
with open(dataPath) as my_file:
答案 0 :(得分:0)
import os
path = os.environ['HOMEPATH']
答案 1 :(得分:0)
我首先要弄清楚放置文件的标准位置。在Windows上,USERPROFILE环境变量是一个良好的开端,而在Linux / Mac机器上,您可以依赖HOME。
from sys import platform
import os
if platform.startswith('linux') or platform == 'darwin':
# linux or mac
user_profile = os.environ['HOME']
elif platform == 'win32':
# windows
user_profile = os.environ['USERPROFILE']
else:
user_profile = os.path.abspath(os.path.dirname(__file__))
filename = os.path.join(user_profile, 'doc.txt')
with open(filename, 'w') as f:
# opening with the 'w' (write) option will create
# the file if it does not already exists
f.write('whatever you need to change about this file')
答案 2 :(得分:0)