我正在使用python为侦察小屋编写程序,存储有关侦察员的信息并能够添加/删除侦察员。该规范说它必须使用文件处理来存储侦察员。
在编写remove scouts部分的代码后,我遇到了os.rename()命令的问题。老实说,我不明白为什么。 sed dir实际上并不存在,这是我的问题吗? src目录,我想将其重命名为其他名称。例如,我想重命名" IDTemp.txt" to" 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'
答案 0 :(得分:0)
通过重写代码段来修复它,并将ID从temp复制到主ID文件的新副本,留下ID以删除{{1}}。然后我删除了临时文件。