python3上的FileNotFoundError,即使File确实存在

时间:2015-09-23 11:44:20

标签: python python-3.x

看着有类似问题的其他人,通常他们只有一个相对路径,但事实并非如此,我正在使用os.join()获得的完整路径。

这是我的代码:

def reencode(file):
global DEFAULT_GFORMAT
global DEFAULT_VCODEC
global DEFAULT_ACODEC
global containerformat
global input
filename = os.path.join(input, file)

Container = 0
Video = 0
Audio = 0

if changeContainer:  # The container needs to be changed
    Container = DEFAULT_GFORMAT
else:  # Container is already fine
    Container = "copy"
if reencodeVideo:  # Video codec needs to be changed
    Video = DEFAULT_VCODEC
else:  # Video codec is already fine
    Video = "copy"
if reencodeAudio:  # Audio codec needs to be changed
    Audio = DEFAULT_ACODEC
else:  # Audio codec is already fine
    Audio = "copy"
if(Container == "copy" and Video == "copy" and Audio == "copy"):
    print("{}: File is playable by the fire tv stick".format(file))
    print()
else:  # File needs to be reencoded
    name = os.path.splitext(file)[0]  # This removes the file extension from the name
    if(containerformat == "MPEG-4"):  # We only need to check for mp4 since if it's not mp4 it's either mkv or it's gonna be reencoded to mkv
        newName = name + ".mp4"  # This is the new name for the output file
    else:
        newName = name + ".mkv"  # This is the new name for the output file
    print("Reencoding file...")
    filename2 = shlex.quote(filename)
    print(filename2)
    os.rename(filename2, (filename + ".bak"))  # File needs to be renamed so it's not overwritten
    x = (input) + ".bak"
    y = shlex.quote(x)
    z = shlex.quote(newName)
    command = "ffmpeg -loglevel error -stats -i " + y + " -map 0 -scodec copy -vcodec " + Video + " -acodec " + Audio + " " + z
    try:
        subprocess.call(command, shell=True)  # Run the command
    except OSError as e:  # Some error happened
        if e.errno == os.errno.ENOENT:  # ffmpeg is not installed
            print("ffmpeg does not seem to be installed. Please install it if you want to run this script")
        else:  # Something else went wrong
            raise
    print()  # Just to make it look a little nicer

错误发生在这里:

os.rename(filename2, (filename + ".bak"))

完整的错误消息是:

line 153, in reencode
os.rename(filename2, (filename + ".bak"))  # File needs to be renamed so it's not overwritten
FileNotFoundError: [Errno 2] No such file or directory: "'/home/robert/Filme/sex school.mkv'" -> '/home/robert/Filme/sex school.mkv.bak'

正如您所看到的,路径'/ home / robert / Filme / sex school.mkv'是完整路径,而不仅仅是相对路径。当我尝试像

这样的东西时
mpv '/home/robert/Filme/sex school.mkv'

在命令行上,文件播放没有问题,所以路径肯定是正确的。为什么我仍然会收到此错误?

1 个答案:

答案 0 :(得分:2)

您不需要shell扩展引用,因为您没有通过shell重命名。

Ergo,删除此行:

filename2 = shlex.quote(filename)

只需使用:

os.rename(filename, filename + ".bak")

现在,享受你的性学校视频。