【问题标题】:Analagous operations to achieve os.path.split in Python?在 Python 中实现 os.path.split 的类似操作?
【发布时间】:2013-10-03 21:00:35
【问题描述】:

我一直在 OSX 上使用 Automator [根据之前的问题] 并且 我的 os.path.split 不工作 出于某种原因,即使它是在 CodeRunner 和终端中运行良好的相同代码。 ..

有没有其他方法可以实现这个功能:

import os
input = '/Users/Opus_Magnum/desktop/list.txt'
output = 'test_output.txt'

dir,file = os.path.split(input)
temp_out= os.path.join(dir,output)
out_file=open(temp_out,'w')

print dir
print file
print temp_out

>> /Users/Opus_Magnum/desktop
>> list.txt
>> /Users/Opus_Magnum/desktop/test_output.txt

我基本上是在尝试在与输入文件相同的目录中创建一个新文件

我想知道是什么导致我的os.path.split 函数无法工作,但如果有类似的东西可用,那么我想这也可以工作。

【问题讨论】:

  • 你怎么知道它不起作用?它打印的是什么?有错误吗? (定义不工作
  • 一切正常,直到我到达 dir,file = os.path.split(input) 行。 . .我检查以确保输入字符串正确且所有内容stackoverflow.com/questions/18970231/…
  • 再一次,你只是说有问题,而不是问题是什么......请发布回溯或告诉我们你不期望发生的事情(即文件在directoy X中创建时我希望目录 Y)
  • 再一次,你只是说有问题,而不是问题是什么......请发布回溯或告诉我们你不期望发生的事情(即文件在directoy X中创建时我希望目录 Y)
  • 对此感到抱歉:( automator 在日志中没有告诉我太多,只是告诉我错误在哪一行。当我在 CodeRunner 中运行它时,它运行良好。在 automator 中它没有打印任何内容只是停止运行

标签: python function directory operating-system os.path


【解决方案1】:

您可以使用os.path.dirname()获取输入文件的目录。

input = '/Users/Opus_Magnum/Desktop/list.txt'
input_dir = os.path.dirname(input)
output = 'test_output.txt'
temp_out = os.path.join(input_dir, output)

【讨论】:

    【解决方案2】:
    dir = os.path.dirname(input)
    file = os.path.basename(input) 
    

    类似于

    dir,file = os.path.split(input)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-16
      • 2011-01-31
      • 2018-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多