[英]os.rename(src,dir) cannot find specified file?
我正在使用python编写用于侦察兵小屋的程序,以将信息存储在侦察兵中,并能够添加/删除侦察兵。 规范说它必须使用文件处理来存储侦察员。
在为remove 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
。 然后,我删除了临时文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.