【问题标题】:How to concatenate strings in python如何在python中连接字符串
【发布时间】:2020-10-26 18:08:00
【问题描述】:

我试图通过连接两个字符串在 Python 中运行一个命令,每个字符串都有一个绝对路径。它抛出一个错误。以下是供参考的代码和错误。请纠正我哪里出错了。

代码:

def test_execute_resources_temp_dir(self):
sourcePath = Path("Gemini_logo.png").absolute()
print(sourcePath)
with tempfile.TemporaryDirectory() as tmpdirname:
    destination = Path(tmpdirname).resolve("Gemini_logo_converted.jpg")
    print('created temporary directory', destination)
command = "magick convert" + sourcePath +" "+ destination
formatConversion = FormatConversion()
formatConversion.executeCommand(command)

错误:

TypeError:只能将 str(不是“WindowsPath”)连接到 str test_FormatConversion.py:65: TypeError

【问题讨论】:

  • 你在网上搜索过这个吗?
  • 是的,我已经完成了。我从研究中了解到 - 它将“magick convert”作为字符串,并且 (sourcePath +" "+ destination) 是 Windows 路径。它建议使用单引号和双引号(将整个命令作为单个字符串给出)。尝试使用它,仍然出现错误(不存在此类文件)

标签: string concatenation


【解决方案1】:

您可以将sourcePath 替换为str(sourcePath)。

同样,您可以将destination 替换为str(destination)

command = "magick convert" + str(sourcePath) +" "+ str(destination)

【讨论】:

  • 谢谢 Wyck,我已经尝试了下面的代码,它成功了。
【解决方案2】:

这对我有用

def test_execute_resources_temp_dir(self):
        os.chdir('..')
        sourcePath = Path("src\\resources\\Gemini_logo.png").absolute()
        print(sourcePath)
        with tempfile.TemporaryDirectory() as tmpdirname:
            # os.mkdir(os.path.basename(tmpdirname))
            destination = Path(tmpdirname+"/Gemini_logo_converted1.jpg")
            print('created temporary directory', destination)
            command = **"magick convert"+" "+ str(sourcePath) + " " + str(destination)**

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-15
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    • 2012-12-04
    • 1970-01-01
    • 2011-10-11
    相关资源
    最近更新 更多