文件夹中的Python顺序文件不工作

2024-05-29 11:10:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Python创建了一个脚本,可以在文件夹中插入具有相同文件扩展名的文件。在Windows上工作正常,在Mac操作系统上存在问题。我附上我收到的代码和错误

import os
import shutil

percorso = input("Inserisci il percorso ")
os.chdir(percorso)

for f in os.listdir():
    f_name, f_ext = os.path.splitext(f)
    f_new = f_ext[1:len(f_ext)]

    
    if os.path.isdir(f) or os.path.isdir('/Users/net/Downloads/.DS_Store'):
        pass
        print("sono una cartella")
    else:
        print("sono un file")

        #is_dir = os.path.exists(r"C:\Users\LUIS\Desktop\prova" + f_new)
        #print(is_dir)
        
        try:
            os.mkdir(f_new)
            print("cartella creata")
        except FileExistsError:
            pass
            print("File inseriti nelle rispettive cartelle")
        except FileNotFoundError:
            print("Tutti i file sono stati ordinati")
            
    
        f2 = f_name+f_ext
        shutil.move(f2, f_new)
        

这是我得到的错误:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/shutil.py", line 803, in move
    os.rename(src, real_dst)
FileNotFoundError: [Errno 2] No such file or directory: '.DS_Store' -> ''

有什么帮助吗?谢谢


Tags: 文件pathnameinimportnewos错误
1条回答
网友
1楼 · 发布于 2024-05-29 11:10:35

这个问题与隐藏的OSX文件有关,它们遵循.name模式,在这些情况下,它们的变量“f_ext”是空的,因此f_new也是空的。 当您尝试移动文件“shutil.move(f2,f_new)”时,会抛出一个错误

我做了,我创建了一个小条件来检验这个假设,它在我的Macbook上运行得非常好

import os
import shutil

percorso = input("Inserisci il percorso ")
os.chdir(percorso)

for f in os.listdir():
    f_name, f_ext = os.path.splitext(f)
    print(os.path.splitext(f))

    if f_ext: # <      HERE
        f_new = f_ext[1:len(f_ext)]
    else:
        f_new = 'no_extension'

    if os.path.isdir(f):
        pass
        print("sono una cartella")
    else:
        print("sono un file")

        try:
            os.mkdir(f_new)
            print("cartella creata")
        except FileExistsError:
            pass
            print("File inseriti nelle rispettive cartelle")
        except FileNotFoundError:
            print("Tutti i file sono stati ordinati")

        f2 = f_name + f_ext
        shutil.move(f2, f_new)

其他检查,就像文件夹已经存在一样,只有在没有同名词的情况下才需要创建新文件夹。但这个代码是有效的

相关问题 更多 >

    热门问题