【问题标题】:what is the correct or best way to input a users home path address into a string?将用户主路径地址输入字符串的正确或最佳方法是什么?
【发布时间】:2020-11-06 21:29:38
【问题描述】:

你好,正如标题所说,我正在编写一个从 chrome 复制数据的程序。我当前的代码是

#library imports
import sys
import shutil
import os
import subprocess


#search and find requried files.

os.path.expanduser('~user') #search for user path

#Making directory
newpath = r'F:\Evidence\Chromium'
newpath = r'F:\Evidence\Chrome'

#Copy chrome file
original = r'%LOCALAPPDATA%\Google\Chrome\User Data\Default\History'
target = r'F:\Evidence\Chrome'
shutil.copyfile(original, target)

我在original = r'%LOCALAPPDATA%\Google\Chrome\User Data\Default\History'一行收到一个错误

我假设脚本无法读取%LOCALAPPDATA%\ 并且需要正确的用户路径? 在windows电脑上输入用户目录需要什么代码?

例如C:\Users\(Script to find out this part)\AppData\Local\Google\Chrome\User Data\Default

Scripv3.py", line 25, in <module>
shutil.copyfile(original, target)
File "C:\Users\darks\AppData\Local\Programs\Python\Python39\lib\shutil.py", line 261, in copyfile
with open(src, 'rb') as fsrc, open(dst, 'wb') as fdst:
FileNotFoundError: [Errno 2] No such file or directory: '%LOCALAPPDATA%\\Google\\Chrome\\User Data\\Default\\History'

【问题讨论】:

  • 请发布带有完整错误文本的回溯消息。
  • 无法复制。 shutil.copyfile 上会出现错误是有道理的,因为 %LOCALAPPDATA% 没有展开,但文字字符串分配本身没有我可以看到的问题。
  • stackoverflow.com/questions/13184414/… 的可能重复项;不过,如果不立即结束问题,我不能投票结束自己。

标签: python path


【解决方案1】:

使用pathlib 库。

from pathlib import Path

original = Path.home() / "Google/Chrome/User data/Default/History"
target = Path("F:/Evidence/Chrome")

shutil.copyfile(origina, target)

【讨论】:

  • 可以删除;这没有解决使用%LOCALAPPDATA% 指定特定目录的问题。
【解决方案2】:

您要做的是在original 变量上使用os.path.expandvars() 函数:

os.path.expandvars(r'%LOCALAPPDATA%')

将返回:

C:\Users\USERNAME\AppData\Local

其中USERNAME 是当前用户的名称。

因此,请确保为该路径扩展变量:

original = os.path.expandvars(original)

shutil.copy(original, target)使用之前

【讨论】:

  • 感谢您提供的解决方案,我将在明天尝试,看看是否有任何进展。
猜你喜欢
  • 1970-01-01
  • 2011-12-14
  • 1970-01-01
  • 2020-11-20
  • 2017-09-03
  • 2018-09-18
  • 2011-01-08
  • 2014-09-04
  • 1970-01-01
相关资源
最近更新 更多