使用shutil.move()指定不存在目标路径后文件丢失,求定位文件位置
Hey, let's figure out where your files ended up—this is a super common gotcha with shutil.move()!
The Short Answer
Your files weren't actually "lost"—they just got renamed to a file named Docs in the current working directory where you ran your Python script. They no longer have their original .docx/.doc suffix, so they might look like unknown files at first glance.
Why This Happened
Let's break down the behavior of shutil.move() in your scenario:
- When you pass a target path that doesn't exist (like
"Docs"),shutil.move()doesn't automatically assume you meant a directory—it treats"Docs"as a new filename instead of a folder. - So instead of moving the file into a non-existent
Docsdirectory, it renames the source file toDocsand moves it to the folder you were in when you ran the script.
Example to Make It Clear
Suppose:
- Your script runs from
/home/you/workspace/ - Your source file is
/home/you/files/notes.doc - You execute
shutil.move("/home/you/files/notes.doc", "Docs")
The end result? The file becomes /home/you/workspace/Docs—no .doc extension, but it's still the exact same Word file under the surface.
How to Get Them Back
- First, find the current working directory of your script:
- If you still have the script, add
print(os.getcwd())at the top and run it again—it will show you exactly where the script was running from. - Or just think back to the folder you were in when you typed the command to run the Python script.
- If you still have the script, add
- Navigate to that directory, look for a file named
Docs(no extension). - Rename it back to its original name (e.g.,
notes.doc)—it will open normally like any other Word file.
How to Avoid This Mistake Next Time
To explicitly tell shutil.move() you're targeting a directory (not a filename), add a trailing slash to the path:
shutil.move(os.path.join(root, f), "Docs/") # The trailing slash signals this is a directory
Now, if the Docs directory doesn't exist, shutil.move() will throw an error instead of silently renaming your files—way safer!
内容的提问来源于stack exchange,提问作者mg520

