繁体   English   中英

使用Python将文件从一个目录移动到另一个目录时无法解决错误

[英]Can't resolve error while moving files from one directory to another directory with Python

我有一个问题
“创建一个程序来读取目录'Task2'中文件的名称,名称格式为UmSn,其中m=1 to 40n=1 to 40将文件分成基于m不同目录,如U1,U2,U3......U40 。”
提示:使用“ os”模块读取目录和文件名。
我试图解决它,但不能解决。
这是我的代码。

import shutil
import os,fnmatch
os.chdir("D:/MCS 2/MCS4/SL/Task2")
for i in range(1,41):
    os.mkdir("U"+str(i))
files = os.listdir()
pattern = "*.TXT"

for i in range(1,41):
    for f in files:
        if f.startswith("U"+str(i)) and fnmatch.fnmatch(f, pattern):
            shutil.move(f,("U"+str(i))) 

我尝试了很多,但无法解决此错误。

  Traceback (most recent call last):
  File "C:\Users\kaleemi\AppData\Local\Programs\Python\Python37-32\lib\shutil.py", line 557, in move
    os.rename(src, real_dst)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'U10S1.TXT' -> 'U10\\U10S1.TXT'

文件以U1 T0 U9开头U1 T0 U9移动成功,但在移动U10S1.TXT产生错误。
因此,文件U10S1.TXT也存在于目录中。
请帮助我找到我在代码中做错的地方。

也许您可以尝试确保使用os.path.abspath()代替提供绝对路径:

from os.path import abspath
...
shutil.move(abspath(f),("U"+str(i))) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM