Python os.rename(src,dir)找不到指定的文件?
我正在用python为一个童子军小屋编写一个程序,用来存储童子军的信息并能够添加/删除童子军。该规范说,它必须使用文件处理来存储侦察兵 在编写remove scouts部分的代码时,我遇到了os.rename()命令的问题。我真的不明白为什么。sed目录实际上并不存在,这是我的问题吗?src dir没有,我想将其重命名为其他名称。例如,我想将“IDTemp.txt”重命名为“IDs.txt”,而不将“IDs.txt”实际作为文件存在。这可能吗? 代码如下:Python os.rename(src,dir)找不到指定的文件?,python,file,io,rename,Python,File,Io,Rename,我正在用python为一个童子军小屋编写一个程序,用来存储童子军的信息并能够添加/删除童子军。该规范说,它必须使用文件处理来存储侦察兵 在编写remove scouts部分的代码时,我遇到了os.rename()命令的问题。我真的不明白为什么。sed目录实际上并不存在,这是我的问题吗?src dir没有,我想将其重命名为其他名称。例如,我想将“IDTemp.txt”重命名为“IDs.txt”,而不将“IDs.txt”实际作为文件存在。这可能吗? 代码如下: elif self._name ==
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
。然后我删除了临时文件。在哪里创建了IDTemp
?如果sctID!=remID
?@cdarke代码得到了很好的注释。如上所述,如果ID不是我们要删除的ID,则该行将写入临时文件。IDTemp是在我的主类中创建的,当程序运行时,您需要源文件存在,而它不。。。如果您有疑问,请使用os.path.exists并打印(或raise…)。@Ericleveil源文件确实存在于该点,因为它是在使用open(IDTemp,“a”)调用ft时创建的。使用实际的tempfile将是一个更好的实现,您也不必总是调用readlines,只需在file对象上迭代即可