我做了一个python下载分类器,但有一个小错误称为[WinError 3]系统找不到指定的路径:''

70gysomp  于 2022-12-28  发布在  Python
关注(0)|答案(2)|浏览(203)

问题是在运行名为this的脚本时出现错误
terminal log脚本如下:

import os

# Get a list of all the files in the current directory
files = os.listdir('.')

# Sort according to extention
files.sort(key=lambda x: x.split('.')[-1])

# for loop to itrate thru list
for file in files:
  # base name and extention split eg. joe .mama (folder: mama; folder chya andar: joe)
  name, extension = os.path.splitext(file)

  #pahale directory banwachi, if dosent exist
  directory = extension[1:]
  if not os.path.exists(directory):
    os.makedirs(directory)
  

  # Move the file into the directory for its file extension
  os.rename(file, f'{directory}/{file}')

任何帮助将不胜感激感谢:)〈3
当我第一次运行时脚本工作正常,但当我第二次运行时出现此错误

68bkxrlz

68bkxrlz1#

你的代码没有处理没有扩展名的文件,添加一些处理。例如;

import os

# Get a list of all the files in the current directory
files = os.listdir('.')

# Sort according to extention
files.sort(key=lambda x: x.split('.')[-1])

# for loop to itrate thru list
for file in files:
  # base name and extention split eg. joe .mama (folder: mama; folder chya andar: joe)
  name, extension = os.path.splitext(file)

  #pahale directory banwachi, if dosent exist
  directory = extension[1:] if extension[1:] != '' else 'None'
  if not os.path.exists(directory):
    os.makedirs(directory)
  

  # Move the file into the directory for its file extension
  os.rename(file, f'{directory}/{file}')
bfhwhh0e

bfhwhh0e2#

这是我写的代码的更好版本

import os
import shutil

# Sort and move files according to their extension

# Get a list of all the files in the current directory
files = os.listdir('.')

# Sort the files by extension
files.sort(key=lambda x: os.path.splitext(x)[1])

# Iterate through the files
for file in files:
  # Split the file name and extension
  name, extension = os.path.splitext(file)

  # Create the destination directory for the file
  if extension != '':
      directory = extension[1:]
      if not os.path.exists(directory):
          os.makedirs(directory)
  else:
      directory = 'None'

  # Move the file to the destination directory
  shutil.move(file, os.path.join(directory, file))

谢谢你的帮助:)

相关问题