【问题标题】:Specifying a partial path for os.path.join为 os.path.join 指定部分路径
【发布时间】:2017-08-29 12:56:26
【问题描述】:

我有一个 python 脚本,它创建一个 PDF 并将其保存在保存脚本的文件夹的子文件夹中。我有以下将文件保存到子文件夹:

outfilename = "Test" + ".pdf" #in real code there is a var that holds the name of the file
outfiledir = 'C:/Users/JohnDoe/Desktop/dev/PARENTFOLDER/SUBFOLDER/' #parent folder is where the script is - subfolder is where the PDFs get saved to
outfilepath = os.path.join(outfiledir, outfilename)

有没有一种方法可以将 PDF 保存到子文件夹而无需指定完整路径?假设我想让这个脚本成为多台计算机可以使用的 exe,我将如何显示路径以便将 PDF 保存在子文件夹中?

谢谢!

【问题讨论】:

  • 我通常会让脚本接受一个参数(通过命令行或在配置文件中)以传递到输出目录。比如:python <myscript> -o /path/to/outdirdocs.python.org/3/library/argparse.html

标签: python python-3.x


【解决方案1】:

试试看:

import os
dir_name = os.path.dirname(os.path.abspath(__file__)) + '/subdir'
path = os.path.join(dir_name, 'filename')

【讨论】:

  • 您介意解释一下os.path.abspath(__file__) 部分的作用吗?
  • 当然,__file__ 是模块属性,它保存了该模块的路径。
猜你喜欢
  • 1970-01-01
  • 2013-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-31
  • 1970-01-01
  • 2023-03-31
  • 2016-08-19
相关资源
最近更新 更多