在其他模块调用readData模块,发现找不到某个文件。如果直接通过readData模块,就不会有问题。我对这个问题很感兴趣,那么现在就开始解决这个问题吧?
通过上述问题描述,我们可以知道该文件的路径没有问题。只是调用过程,出现某种原因导致无法找到路径。我们先看看报错信息:
C:\Users\lenovo\AppData\Local\Programs\Python\Python37\python.exe D:/360MoveData/Users/lenovo/Desktop/startProject/OAS.Cloud.PAAS_Interface/TestCases/UM/Test_01_register.py
Traceback (most recent call last):
File "D:/360MoveData/Users/lenovo/Desktop/startProject/OAS.Cloud.PAAS_Interface/TestCases/UM/Test_01_register.py", line 70, in <module>
path = readCase.readCasedata("UM", "Test_01").getPath()
File "D:\360MoveData\Users\lenovo\Desktop\startProject\OAS.Cloud.PAAS_Interface\common\readCase.py", line 28, in getPath
row = self.getCase()
File "D:\360MoveData\Users\lenovo\Desktop\startProject\OAS.Cloud.PAAS_Interface\common\readCase.py", line 18, in getCase
self.wb = load_workbook(filename='caseModel.xlsx', read_only=True)
File "C:\Users\lenovo\AppData\Local\Programs\Python\Python37\lib\site-packages\openpyxl\reader\excel.py", line 313, in load_workbook
data_only, keep_links)
File "C:\Users\lenovo\AppData\Local\Programs\Python\Python37\lib\site-packages\openpyxl\reader\excel.py", line 124, in __init__
self.archive = _validate_archive(fn)
File "C:\Users\lenovo\AppData\Local\Programs\Python\Python37\lib\site-packages\openpyxl\reader\excel.py", line 96, in _validate_archive
archive = ZipFile(filename, 'r')
File "C:\Users\lenovo\AppData\Local\Programs\Python\Python37\lib\zipfile.py", line 1207, in __init__
self.fp = io.open(file, filemode)
FileNotFoundError: [Errno 2] No such file or directory: 'caseModel.xlsx'
Process finished with exit code 1
在该模块采取的是相对路径,当在本文件运行的时候,该文件会找到当前文件夹的目录。但当他调用的时候,调用它的文件在另一个目录,也许是这个原因导致无法成功调用。这是我的猜想,我们现在去验证它。
f.wb = load_workbook(filename=r'D:\360MoveData\Users\lenovo\Desktop\startProject\OAS.Cloud.PAAS_Interface\common\caseModel.xlsx', read_only=True, )
验证结果:
说明,我们的猜想是正确的。我靠,我真他妈是个天才!
代码迁移到其他地方,总不能不断去更改路径吧?因此,我们通过os模块,来生成绝对路径,由此来解决这个问题。
dir_path = os.path.dirname(os.path.abspath(__file__))
self.wb = load_workbook(filename=os.path.join(dir_path,'caseModel.xlsx'), read_only=True, )