Python 移动名称中带有空格的文件

Python 移动名称中带有空格的文件,python,shutil,Python,Shutil,我试图在python中移动一些文件,但它们的名称中有空格。有没有办法特别告诉python将字符串作为文件名处理 listing = os.listdir(self.Parent.userTempFolderPath) for infile in listing: if infile.find("Thumbs.db") == -1 and infile.find("DS") == -1: fileMover.moveFile(infile, self.Parent.use

我试图在python中移动一些文件,但它们的名称中有空格。有没有办法特别告诉python将字符串作为文件名处理

listing = os.listdir(self.Parent.userTempFolderPath)
for infile in listing:
    if infile.find("Thumbs.db") == -1 and infile.find("DS") == -1:

        fileMover.moveFile(infile, self.Parent.userTempFolderPath, self.Parent.currentProjectObject.Watchfolder, True)

从清单中获取文件后,我在其上运行
os.path.exists
,查看它是否存在,并且它从未存在过!谁能给我一个提示吗?

文件名中的空格不是问题
os.listdir
返回文件名,而不是完整路径

您需要将它们添加到文件名中以测试它们;将使用适用于您的平台的正确目录分隔符为您执行此操作:

listing = os.listdir(self.Parent.userTempFolderPath)
for infile in listing:
    if 'Thumbs.db' not in infile and 'DS' not in infile:
        path = os.path.join(self.Parent.userTempFolderPath, infile)

        fileMover.moveFile(path, self.Parent.userTempFolderPath, self.Parent.currentProjectObject.Watchfolder, True)

注意,我还简化了文件名测试;不要使用
.find(..)=-1
我使用
not in
操作符。

可能重复的…并且出于对所有神圣事物的热爱,不要使用find()作为子字符串的存在。在这种情况下,在使用相对路径之前,请在中使用
,或者在
中不使用
。或者在使用相对路径之前使用
os.chdir(self.Parent.userTempFolderPath)
。@KurzedMetal:如果从脚本运行外部命令,则会产生其他令人惊讶的效果。最好坚持绝对路径。更改目录没有什么奇怪的,可能是在不应该或没有手动设置当前目录时使用相对路径。重要的问题是。。。您是否真的运行外部命令而不仔细检查您是否在正确的目录中?我不知道。@KurzedMetal:显式比隐式好;绝对路径消除了对上下文的需要。