Python: joins() 太多了?

Python: too many joins()?

我不确定为什么会出现此错误,我在脚本的不同位置使用了 str.join()os.path.join(),是这个原因吗?

使用os.path.join:

from os.path import getsize, dirname, join

class Wav:
    src_path = "No path"
    dest_path = destination
    old_name = "name.wav"
    new_name = ""

    def __init__(self, path):
        self.src_path = path
        self.old_name = os.path.split(path)
        self.new_name = self.old_name
        self.dest_path = join(destination, self.new_name) # error here

这是我的错误:

Traceback (most recent call last):  
  File "call.py", line 132, in <module>  
    temp = Wav(temp_path)  
  File "call.py", line 32, in __init__  
    self.dest_path = join(destination, self.new_name)  
  File "/usr/lib/python2.7/posixpath.py", line 75, in join  
    if b.startswith('/'):  
 AttributeError: 'tuple' object has no attribute 'startswith'  

这是与 str.join() 冲突还是我没有正确导入 os.path

self.dest_path = join(destination, self.new_name) # error here

self.new_name 不是一个字符串,它是一个元组,所以你不能用它作为 join 的第二个参数。也许您打算仅使用 self.new_name 的最后一个元素加入 destination

self.dest_path = join(destination, self.new_name[1])

self.new_name 是一个元组,而不是代码中的字符串,并且 os.path.join 接受一个字符串列表,而不是一个字符串和一个列表。你可以用

self.dest_path = join(destination, *self.new_name)

self.new_name作为参数扩展到os.path.join

  1. 检查 destination 和 self.new_name 是否是列表或。元组

元组(它们看起来是这样的:

mytup = ('hey','folk')

) 没有属性开头。你必须使用字符串。要检查这一点,只需在程序中打印出变量即可。

  1. 我不认为 join 可以相互替代,但你应该试试。

    进口os.path

将其写在您的第一个导入行下。然后替换

加入(...,...)

os.path.join(...,...)

如果您想使用 os.path 模块。