while True:
try:
enterName = input("Enter the name of the file:") + ".txt"
latinFile = open(enterName,"r")
read = latinFile.readlines()
for lines in read:
store.append(lines.strip())
checkSquare (store)
print ("File:")
for content in store:
print (content)
saveData(store)
我认为问题出在保存文件内容的代码上。 目的是让代码打开文件,读取内容并检查文件格式是否正确等,然后如果一切正常并且有效,它将再次保存文件(saveData)但它将重命名该文件,以便它在目录中显示它已经过验证。
但是,代码不工作(os.rename 部分)而且我不断收到权限错误,我不知道如何修复它。
错误信息:
Traceback (most recent call last):
File "C:\Users\---\Desktop\python\idkll.py", line 44,in <module>
saveData(store)
File "C:\Users\---\Desktop\python\idkll.py", line 18, in saveData
os.rename (fileName,"VALIDATED" + fileName)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'OPENEDve.txt'
请您参考如下方法:
您应该在完成读取或写入文件后立即关闭文件。并且您应该在尝试重命名之前关闭该文件。您可以使用文件的 .close() 方法,或使用 with 语句,以便文件自动关闭。
顺便说一句,您的 saveData() 函数可能不应该提示用户输入文件名:只需将您在 enterName 中已有的名称传递给它即可。此外,在文件名前加上 "VALIDATED" 也不是一个好的策略。如果您只是在当前目录中使用相对文件名,那没关系,但这会使正确的文件路径变得一团糟。
响应更新:
saveFile 不 包含文件名字符串,它是一个代表您打开的文件的 Python 对象(也称为文件句柄)。该文件的名称是 enterName 中的字符串。所以你需要做类似的事情
os.rename(enterName, enterName + "VALIDATED")
