python - 我无法将 xls 文件从一个目录复制到另一个目录
问题描述
我正在尝试制作一个简单的脚本,它给出了一个名称,它创建了一个文件夹,其中包含 5 个子文件夹,并添加了我在其他文件夹中的拼写错误 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 点
首先,我鼓励你使用pathlib
而不是字符串。
Windows 使用反斜杠,如C:\Users\Sam\AppData\
Linux 使用正斜杠C:/Users/Sam/AppData/
使用反斜杠的问题在于字符串具有特殊含义。例如,C:\Users\nanny
将插入一个换行符\n
。
Withpathlib.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 个字符。我认为您想使用文件夹名称中的最后 12 个字符,而不是删除最后 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())
推荐阅读
- r - 字符值问题
- nunit - 如何在命令行上打印 NUnit 测试运行的 XML 文件作为漂亮的报告?
- django - 在 django 通用视图中访问 HTTP_REFERER
- ssh - Gitlab CI/CD:使用 ssh 密钥部署到 ubuntu 服务器(使用 windows shell 运行器)
- c++ - 许多 Boost::histogram 对象的动态分配
- python - 为什么一个 Python 脚本会引发 qt.qpa.plugin 错误,而另一个相同的脚本不会?
- angular - 在 HTTP 单元测试中总是调用 catchError
- javascript - 显示来自现有 img 标签的图像,而无需再次调用服务器。chrome 扩展 javascript
- mysql - 气流:芹菜工人太多的MySQL连接
- r - 将多个输出从闪亮添加到 html 降价