Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

python - I get a FileNotFoundError when I run this Program

I'm dealing with moving files from subfolders to another location to organize my Files. While doing so I encountered some errors from this program.

import os
from shutil import move

src = "C:\Users\User\Desktop\SMALL"
dst = "C:\ALL IN ONE\Temporary Folder"

if not os.path.exists(dst):
    os.makedirs(dst)
for x, y, z in os.walk(src):
    for files in z:
        if files.endswith("txt"):
            move(files, dst)

When I run the program, it raises a FileNotFoundError: [WinError 2] The system cannot find the file specified: '0.txt' -> 'C:\ALL IN ONE\Temporary Folder\0.txt' error and a bunch of other "Traceback Errors" (if that's what they're called)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to construct the source path. Try changing:

move(files, dst)

to:

path = os.path.join(x, files)
move(path, dst)

You might also want to rename files to file, since it's just a single file each time through the loop.

Justin Ezequiel pointed out that including src in the call to os.path.join is incorrect, so I've updated the answer to simply join x and files.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...