我正在 Windows 10 计算机上的 python 3.5 上使用 openpyxl 库,并尝试 load_workbook() 带有空格的路径名。
我在网上查了一下,似乎无法自己解决这个问题。我在下面列出了我的一些尝试。
我一定完全错过了一些东西,因为我找不到其他人询问 openpyxl 的这个特定问题。
任何帮助将不胜感激。
我当前的解决方法是使用 python 来检查并可能重命名文件以删除空格,但这似乎完全没有必要,而且我可能并不总是有这样做的权限。
import openpyxl
from openpyxl import load_workbook
import os
docName = "space book.xlsx"
docNameWithExits = "space^ book.xlsm"
fullPathOfDocument = "./" + docName
fullPathOfDocumentExtraPar = "'" + "./" + docName + "'"
fullOsPath = os.path.join("." , docName)
docObject = open(fullPathOfDocument,"rb")
try:
attempt1 = load_workbook(docName)
print("worked")
except:
print("didnt work")
try:
attempt2 = load_workbook(fullPathOfDocument)
print("worked")
except:
print("didnt work")
try:
attempt3 = load_workbook(fullPathOfDocumentExtraPar)
print("worked")
except:
print("didnt work")
try:
attempt4 = load_workbook(docNameWithExits)
print("worked")
except:
print("didnt work")
try:
attempt5 = load_workbook(fullOsPathvar)
print("worked")
except:
print("didnt work")
try:
attempt6 = load_workbook(docObject)
print("worked")
except:
print("The computer has won")
预先感谢您的帮助问候,-下一步
openpyxl.load_workbook() 可以读取其中包含空格的路径。在我的完全可重现的示例中,工作簿名称和文件夹中有空格。
我猜如果您不在字符串前面加上“r”,就会出现问题。 “r”将告诉 python 将给定的字符串视为原始字符串。
import os
from openpyxl import Workbook
from openpyxl import load_workbook
# Path to be created - please change to your desired folder location
path = r"C:\Users\doe_j\test\python\a path\with spaces"
wb_name = path + r"\space book.xlsx"
if os.path.isdir(path) != True:
os.makedirs(path)
print(path, "created!")
elif os.path.isdir(path) != False:
print(path, "already exists!")
# making a workbook so this example is reproducible
wb = Workbook()
ws = wb.active
ws["A1"] = "Putting some text in"
wb.save(wb_name)
# loading that same workbook
wb = load_workbook(wb_name)
ws = wb.active
ws["A3"] = "Adding Some more text in"
wb.save(wb_name)
此示例在 Windows 10、Python 3.5 和 openpyxl 2.4.7 上进行了测试。
我是一名优秀的程序员,十分优秀!