我无法将xls文件从一个目录复制到另一个目录

时间:2019-11-04 11:59:17

标签: python copy

我正在尝试制作一个简单的脚本,给它一个名称,它创建一个文件夹,并在其中包含5个子文件夹,并在其他文件夹中添加我有的typo-xls。我可以创建文件夹并创建一个Xls,稍后再在此新文件夹中替换它,但似乎无法复制该文件。应该是什么问题?

import os
import time
import shutil
import xlsxwriter
from os.path import join


print("Seja bem-vindo ao programa de Criação de Pastas.")
time.sleep(2)

#Qual a referência

ref=input("Qual a referência que pretende criar? (A,B ou C) : ")
if ref=='A':
    os.chdir(r"\\server\3Via\Referências A - Para Vender")
    dst=r"\\server\3Via\Referências A - Para Vender"
elif ref=='B':
    os.chdir(r"\\server\3Via\Referências B - Parceria")
    dst=r"\\server\3Via\Referências B - Parceria"
elif ref=='C':
    os.chdir(r"\\server\3Via\Referências C - Comprar")
    dst=r"\\server\3Via\Referências C - Comprar"
else :
    print("A referência inserida não está disponível! ")
    time.sleep(2)
    sys.exit()

folder=input("Digite o nome desejado para a pasta principal: ")
if not os.path.exists(folder):   os.makedirs(folder)


#Criação das Pastas 
os.chdir(folder)
os.makedirs('Citius')
os.makedirs('Portal das Finanças')
os.makedirs('Portal da Justiça')
os.makedirs('Racius e BP')
os.makedirs('Docs Importantes')
print("Pastas adicionadas com sucesso! ")
time.sleep(1)

#Copiar check-list para pasta

nomeficheiro='Check-list ' + folder[:-12]

workbook = xlsxwriter.Workbook(nomeficheiro)
workbook.close()

print("Ficheiro Criado com sucesso! ")

time.sleep(1)

src="\\server\3Via\...Docs Tipo"
shutil.copyfile(src=src+"/Check-list interna.xls", dst= dst+folder+nomeficheiro)
print("Check-list adicionada com sucesso! ")
time.sleep(5)

我只希望它替换我已经可以创建的文件。

1 个答案:

答案 0 :(得分:0)

点1

首先,我建议您使用pathlib代替字符串。

Windows使用反斜杠,例如C:\Users\Sam\AppData\ Linux使用正斜杠C:/Users/Sam/AppData/

使用反斜杠的问题是字符串,因为它们具有特殊含义。例如,C:\Users\nanny将插入换行符\n

使用pathlib.Path可以使用正斜杠,而不会出现该问题。

import pathlib
path = pathlib.Path("C:/Users/nanny")

第2点

无需测试即可测试程序 在命令行上一遍又一遍地键入信息。您和其他人将想按一个按钮 做到这一点。

我们不想看到以下内容:

folder=input("Digite o nome desejado para a pasta principal: ")

第3点

一个问题是“ /server/3Via/... Docs Type”不是有效路径。

另一个问题是parent_folder[:-12]从文件夹名称中删除最后12个字符。我认为您要 USE 文件夹名称中的最后12个字符,而不是 删除 。如果文件夹名称较短,则删除最后12个文件夹名称将完全删除该文件夹名称。使用parent_folder[-12:]代替parent_folder[:-12]


第4点

不信任相对路径和chdir。请只使用绝对路径;仅在任何给定时刻知道当前工作目录是什么。


第5点

我写了一些代码。 它产生以下目录树:

server/
    3Via/
        ReferencesA-ForSale/
            abba_dabba_do_xyz/
                Check-listdabba_do_xyz.xlsx
                internalchecklist.xls
                Citius/
                Finance Portal/
                Important Docs/
                Portal of Justice/
                Racius and BP/

代码如下:

import os
import shutil
import xlsxwriter
import pathlib as pl
import sys
import io

path_lookup = {
        'A':pl.Path("/server/3Via/ReferencesA-ForSale"),
        'B':pl.Path("/server/3Via/ReferencesB-Partnership"),
        'C':pl.Path("/server/3Via/ReferencesC-Buy")
    }

def pprint_path_lookup(path_lookup):
    with io.StringIO() as string__stream:
        for key in path_lookup.keys():
            print(
                key.ljust(4), path_lookup[key],
                file = string__stream,
                sep = ""
            )
        msg = string__stream.getvalue()
    return msg

class AI:
    def notify_without_seeking_response(self, *args, sep=" "):
        print(40 * "#")
        print(*args, sep=sep)
        print(40 * "#")

    def notify_and_get_response(self, *args):
        prompt = "\n".join(str(arg) for arg in args)
        prompt = prompt.strip()

        if "reference do you want to create?(A, B or C):" in prompt:
            response = "A"
        elif "desired name for the parent fold" in prompt:
            response = "abba_dabba_do_xyz"
        else:
            msg = "\ncomputer does not understand the prompt"
            msg += "\n"
            msg += prompt
            raise ValueError(msg)
        print(40*"#")
        print(prompt)
        print()
        print(response)
        print(40 * "#")
        return response

class Human:
    def notify_without_seeking_response(self, *args):
        print(*args)

    def notify_and_get_response(self, *args, sep=" "):
        prompt = sep.join(str(arg) for arg in args)
        choice = input(prompt)
        choice = choice.strip()
        return choice


def folder_creation_program(partner):
    return_data = dict()

    partner.notify_without_seeking_response(
        "Welcome to the Folder Creation program."
    )

    path = None
    for _ in range(20):
        options = pprint_path_lookup(path_lookup)
        ref = partner.notify_and_get_response(
            options,
            "What reference do you want to create?(A, B or C):"
        )
        path = path_lookup.get(ref)
        if path:
            break
        else:
            partner.notify_without_seeking_response(
                ref, "is invalid input"
            )

    if not path:
        msg = "failed to enter correct menu input after many tries"
        raise ValueError(msg)

    folder_name = partner.notify_and_get_response(
        "Enter the desired name for the parent folder:"
    )
    folder_name = folder_name.strip()
    folder_path = path / folder_name

    partner.notify_without_seeking_response(
        "Preparing to make:\n",
        folder_path
    )
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)
        partner.notify_without_seeking_response(
            "Successfully made:\n",
            folder_path
        )
    else:
        partner.notify_without_seeking_response(
            "Folder already exists:\n",
            folder_path
        )

    # Folder Creation
    child_folders = [
        'Citius',
        'Finance Portal',
        'Portal of Justice',
        'Racius and BP',
        'Important Docs'
    ]

    for child in child_folders:
        child_path = folder_path / child
        partner.notify_without_seeking_response(
            "Preparing to make folder:\n    ", child_path
        )
        if not os.path.isdir(child_path):
            os.makedirs(child_path)
        else:
            partner.notify_without_seeking_response(
                "folder\n    ", child_path,
                "\nalready exists. Leaving it alone."
            )
    partner.notify_without_seeking_response(
        "Folders added successfully!"
    )

    # create new file
    check_list_path = folder_path / ('Check-list' + folder_name[-12:] + ".xlsx")

    partner.notify_without_seeking_response(
        "Writing checklist to:\n    ",
        str(check_list_path)
    )

    workbook = xlsxwriter.Workbook(check_list_path)
    workbook.close()

    partner.notify_without_seeking_response(
        "File Created Successfully!\n    ",
        str(check_list_path)
    )

    # COPY .xlsx file to somewhere else
    src = check_list_path
    dst = folder_path / "internalchecklist.xls"
    shutil.copyfile(src=src, dst=dst)

    partner.notify_without_seeking_response(
        "Checklist copied successfully!\n    ",
        dst
    )

    return

folder_creation_program(AI())