【问题标题】:How to add directory or make directory to current path and use file如何将目录或制作目录添加到当前路径并使用文件
【发布时间】:2018-02-20 10:13:30
【问题描述】:

我想在当前路径上创建一个目录并在该路径中添加一个 excel 文件并在脚本中使用该 excel 文件....请帮助 目前我在做

my_excel_file = Path(sys.argv[2])
if not my_excel_file.is_file():
    print ("Excel File not exist")
    logging.error("Excel File not exist")
    exit(-2)

但我想在当前路径中添加目录'/tmp/old excel/n.xlsx' 并使用 n.xlsx 文件

【问题讨论】:

  • 不清楚你想要实现什么。您想使用代码在其中创建目录和文件吗?您提供的代码只是从运行时参数中读取文件路径。

标签: python path


【解决方案1】:

如果不存在,此代码将创建一个目录和文件。您也可以写入该文件:

import os

filename = "tmp/old excel/n.xlsx"
if not os.path.exists(os.path.dirname(filename)):
       os.makedirs(os.path.dirname(filename))

with open(filename, "w") as f:
   f.write("content")

【讨论】:

  • 我们可以在 linux 中使用 os.path.exists 吗??
  • 是的,你可以在 linux 中使用
  • 我需要在服务器上运行该脚本...没问题吧?
  • 首先你必须对其进行测试并确保在你的项目中没有任何问题,然后你可以继续前进。
猜你喜欢
  • 1970-01-01
  • 2020-06-02
  • 2018-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-16
  • 1970-01-01
相关资源
最近更新 更多