os.rename(src,dir) 找不到指定的文件?

os.rename(src,dir) cannot find specified file?

我正在为 scout 小屋使用 python 编写一个程序,以存储关于 scout 的信息并能够 add/remove scout秒。规范说它必须使用文件处理来存储 scouts.

在编写删除 scouts 部分的代码时,我遇到了 os.rename() 命令的问题。老实说,我不明白为什么。 sed 目录实际上并不存在,这是我的问题吗? src 目录确实存在,我想将其重命名为其他名称。例如,我想将 "IDTemp.txt" 重命名为 "IDs.txt",而 "IDs.txt" 实际上不作为文件存在。这可能吗? 代码如下:

elif self._name == "rem":
            remID = str(scoutID.get())
            if remID != "":
                #store all the lines that are in the file in a temp file
                with open(fileName,"r") as f:
                    lines = f.readlines()
                    with open(tempFileName,"a") as ft:
                        for line in lines:
                            #splits the line by ',', then takes the last part. It then trims this to remove the '/n' prefix
                            sctID = str(line.split(",")[3])[:-1]
                            if sctID != remID: #if the ID we are looking to remove isn't
                                #the ID of the scout we are currently looking at, move it to the temp file
                                ft.write(line)
                            else:
                                #Remove the scout ID of the scout that is being removed from the ID file
                                with open(IDFileName,"r+") as fi:
                                    lines = fi.readlines()
                                    with open(IDTemp,"a") as ft:
                                        for line in lines:
                                            if line[:-1] != sctID:
                                                ft.write(line)
                        os.rename(IDTemp,IDFileName)

                #remove the main file, then rectrate a new one
                os.remove(fileName)
                file = open(fileName,"a")
                file.close()

                #copy all the lines back to the main file
                with open(tempFileName,"r") as tf:
                    lines = tf.readlines()
                    with open(fileName,"a") as f:
                        for line in lines:
                            f.write(line)
                #finally, delete and recreate the temp file
                os.remove(tempFileName)
                file = open(tempFileName,"a")
                file.close()
            #remove the window    
            master.destroy()

输出:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__
    return self.func(*args)
  File "C:\Users\KRIS\Documents\Python Projects\Scouts\popupWindow.py", line     88, in _callback
    os.rename(IDTemp,IDFileName)
FileNotFoundError: [WinError 2] The system cannot find the file specified:     'C:\Users\KRIS\Scouts\Temp\IDTemp.txt' ->     'C:\Users\KRIS\Scouts\Temp\IDs.txt'

通过重写代码部分修复了它,并将 ID 从 temp 复制到主 ID 文件的新副本,留下要删除的 ID remID。然后我删除了临时文件。