【问题标题】:I have a certain issue moving files with Python我在使用 Python 移动文件时遇到问题
【发布时间】:2022-06-10 21:37:31
【问题描述】:

我用 Python 编写了一个脚本,它允许我根据文件的扩展名将文件移动到另一个文件夹,如果它是音乐文件,那么文件将转到音乐文件夹,依此类推。问题是我必须在目录中运行程序,即使我将它编码为在我输入的文件夹中运行,为了让程序正常工作,如果我在文件夹之外,它会告诉我该文件已经存在于将要移动的文件夹,这是不正确的,所以我必须将自己放在文件夹中并运行脚本以使其按编程方式工作。我在这里有点新,我正在寻找是否可以找到解决方案,但我找不到,如果有人可以帮助我,我将不胜感激。代码如下:

import os
import shutil

docs = [
    ".doc",
    ".docx",
    ".odt",
    ".pdf",
    ".rtf",
    ".txt",
    ".wpd",
    ".xls",
    ".xlsx",
    ".xml",
    ".ppt",
    ".pptx",
    ".pps",
    ".ppsx",
    ".odp",
    ".csv",
    ".py",
    ".pyc",
    ".pyo",
    ".pyw",
    ".c",
    ".cc",
    ".cxx",
    ".h",
    ".hh",
    ".hpp",
    ".hxx",
    ".m",
    ".mm",
    ".pl",
    ".pm",
    ".pyc",
    ".pyo",
    ".rst",
    ".xhtml",
    ".yml",
    ".epub",
]
audio = [".mp3", ".wav", ".wma", ".aac", ".flac", ".ogg"]
images = [" .bmp", ".gif", ".jpg", ".jpeg", ".png", ".psd", ".tiff"]
video = [".avi", ".flv", ".mov", ".mp4", ".mpg", ".rm", ".swf", ".wmv"]
files = [
    ".7z",
    ".arj",
    ".bz2",
    ".cab",
    ".gz",
    ".rar",
    ".tar",
    ".tgz",
    ".zip",
    ".deb",
    ".iso",
    ".rpm",
    ".msi",
    ".exe",
    ".AppImage",
    ".flatpakref",
]
vpn = [".ovpn"]
fonts = [" .ttf", ".otf", ".woff", ".woff2"]


dir = input("Enter the directory: ")
path=os.listdir(dir)


def is_audio(file):
    return os.path.splitext(file)[1] in audio


def is_image(file):
    return os.path.splitext(file)[1] in images


def is_video(file):
    return os.path.splitext(file)[1] in video


def is_doc(file):
    return os.path.splitext(file)[1] in docs


def is_file(file):
    return os.path.splitext(file)[1] in files


def is_vpn(file):
    return os.path.splitext(file)[1] in vpn


def is_font(file):
    return os.path.splitext(file)[1] in fonts


for file in path:
    try:
        if is_audio(file):
            shutil.move(file, "/home/zephyr/Music")
            print("Moved " + file + " to Music")

        elif is_image(file):
            shutil.move(file, "/home/zephyr/Pictures")
            print("Moved " + file + " to Pictures")

        elif is_video(file):
            shutil.move(file, "/home/zephyr/Videos")
            print("Moved " + file + " to Videos")

        elif is_doc(file):
            shutil.move(file, "/home/zephyr/Documents")
            print("Moved " + file + " to Documents")

        elif is_file(file):
            shutil.move(file, "/home/zephyr/Programs")
            print("Moved " + file + " to Programs")

    except:
        print(f"{file} Not Moved {FileExistsError}")
        pass

【问题讨论】:

  • 您在输入提示符下输入的是绝对路径还是相对路径?
  • 请提供足够的代码,以便其他人更好地理解或重现问题。

标签: python-3.x automation


猜你喜欢
  • 2019-10-02
  • 2021-05-10
  • 1970-01-01
  • 1970-01-01
  • 2022-11-16
  • 2019-12-22
  • 2021-11-27
  • 2020-09-10
  • 1970-01-01
相关资源
最近更新 更多