简体   繁体   English

如何在 python 3.9 中使用 %APPDATA% 获取文件?

[英]How to get a file using %APPDATA% in python 3.9?

I want to store in a variable this path APPDATA%/Roaming/FileZilla/sitemanager.xml .我想将此路径存储在变量中APPDATA%/Roaming/FileZilla/sitemanager.xml

When i use:当我使用:

file = "C:/Users/MyPC/AppData/Roaming/FileZilla/sitemanager.xml"

it works, but when i use:它有效,但是当我使用时:

file = "%APPDATA%/Roaming/FileZilla/sitemanager.xml"

the file cannot be stored and i cant send via paramiko.该文件无法存储,我无法通过 paramiko 发送。

Anyone helps?有人帮忙吗?

You can retrieve the env variable with getenv function from os module.您可以使用getenv function 从os模块检索环境变量。 You can also use Path to easily manipulate paths.您还可以使用Path轻松操作路径。

import os
import pathlib

appdata = pathlib.Path(os.getenv('APPDATA'))
xmlfile = appdata / 'FileZilla' / 'sitemanager.xml'

You can use os.path.expandvars to expand environment variables in a string.您可以使用os.path.expandvars来扩展字符串中的环境变量。 On Windows, $ and % forms are accepted.在 Windows 上,接受 $ 和 % forms。

import os
file = os.path.expandvars("%APPDATA%/Roaming/FileZilla/sitemanager.xml")

(Note the leading %) (注意领先的 %)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在%APPDATA%文件夹python中写入文件 - How to writea file in %APPDATA% folder python Python 3.9 - 如何打印和格式化 .txt 文件? - Python 3.9 - How to print and format a .txt file? 如何使用 Python(首选 3.9)有效地读取和删除具有自定义换行符的大文件的特定行? - How to efficiently read and delete a specific line of a large file with a custom newline character using Python (3.9 preferred)? 使用3.9中的pandas将csv文件导入python但失败“找不到文件” - Importing csv file into python using pandas in 3.9 but it failed "file not found" 如何在 Python 中获取 %APPDATA% 目录的路径? - How can I get the path to the %APPDATA% directory in Python? "Python 3.9 以二进制形式打开文件" - Python 3.9 open file as binary Pyhton 3.9 如何从导入的 python 文件更新列表 - Pyhton 3.9 How to update a list from an imported python file 如何在Python 3.9 PySpark package 内升级一个jar 文件依赖? - How upgrade a jar file dependency within the Python 3.9 PySpark package? 如何为 Python 3.9 安装 PyCrypto? - How to install PyCrypto for Python 3.9? 没有 Python 在 'C:\Users\PC\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\python.exe' - No Python at 'C:\Users\PC\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\python.exe'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM