【问题标题】:How to check if a file is in a certain directory then to pop error if it is not there if it is not there then add it如何检查文件是否在某个目录中然后弹出错误如果它不存在如果它不存在然后添加它
【发布时间】:2020-02-20 03:00:22
【问题描述】:

我们从电子邮件下载 GPX 文件,我想运行一个脚本来选择 GPX 并说明它是否存在或只是将 GPX 添加到另一个文件中。

我有一个脚本,它将 GPX 添加到一个文件中,但我需要它来检查它是否已经在文件中并警告我们,脚本中的这部分不起作用。

    import glob
    import os.path
    import shutil

    SRC_DIR = 'C:/Work'
    TARG_DIR = 'C:/Work/GPS_N32'

    GLOB_PARMS = "*.gpx"

    for file in glob.glob(os.path.join(SRC_DIR, GLOB_PARMS)):
        if file not in glob.glob(os.path.join(TARG_DIR, GLOB_PARMS)):
            shutil.copy(file,TARG_DIR)
        else:
            print("{} exists in {}".format(
                file,os.path.join(os.path.split(TARG_DIR)[-2:])))

错误信息应该是这个gpx已经存在了!如果 gpx 不存在,则应显示已添加文件的消息。

【问题讨论】:

  • 这段代码无论如何都不会运行,因为dir_src + filename 不会给出任何真实的文件路径,因为你会丢失` at the end of dir_src`。你试过运行它吗?
  • 是的,我已经运行了它,但是我收到一个错误,然后弹出另一个文件 shutil.py?然后它以红色显示 this --> with open(src, 'rb') as fsrc:
  • 这正是我所说的错误。阅读如何格式化文件路径,以及如何检查文件存在 - 特别是阅读 os.pathpathlib 看看哪个适合你
  • 好的,所以我也有我在上面编辑的其他代码现在它复制了文件但从不给出错误。问题是 else: 语句吗?
  • glob 是一个生成器,检查是否有 in 它将耗尽它。尝试用list(glob.glob(...)) 替换你所有的glob.glob(...) 以避免这种情况

标签: python arcgis gpx


【解决方案1】:
import glob
import os.path
import shutil

SRC_DIR = r"C:\Work"
TARG_DIR = r"G:\GPS\_in\Trimble\GPS_NEW"
GLOB_PARMS = "*.gpx"

os.chdir(SRC_DIR)

for gpxfile in glob.glob(GLOB_PARMS):

if os.path.exists(os.path.join(TARG_DIR, gpxfile)):

    print("{} already exists in {}".format(gpxfile, TARG_DIR))
else:
    shutil.copy(gpxfile, TARG_DIR)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-07
    • 2015-11-12
    • 2020-10-11
    • 2013-04-29
    • 1970-01-01
    • 2015-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多