xlwings 调用了一个应该创建文件的 python 函数,但没有创建文件
xlwings calls a python function that should create a file, but no file get created
def create_file():
file_writer= open('testFile.txt','w')
file_writer.write('TESTING...;\n')
file_writer.flush()
file_writer.close()
def my_macro():
wb = Workbook.caller() # Creates a reference to the calling Excel file
Range('Sheet1', 'C3').value = random.randint(0,10)
updateValue = Range('Sheet1', 'C3').value
print("updatedValue=" , updateValue);
create_file()
if __name__ == '__main__':
path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'FirstExcel.xlsm'))
Workbook.set_mock_caller(path)
my_macro()
当我在 Eclipse 中 运行 以上代码时,它会创建一个文件并更新 excel 电子表格。但是,当我从 excel 运行 它更新电子表格时,它不会创建文件。
问题是 Excel 当前在与从 Python 调用文件时不同的工作目录中启动 Python 解释器。这是 GitHub 上的未决问题,请参阅 here。
同时,只需为 open
和 write
中的所有文件使用 absolute/full 路径。您还应该能够使用 os.path.abspath(os.path.join(os.path.dirname(__file__), 'testFile.txt'))
之类的东西
def create_file():
file_writer= open('testFile.txt','w')
file_writer.write('TESTING...;\n')
file_writer.flush()
file_writer.close()
def my_macro():
wb = Workbook.caller() # Creates a reference to the calling Excel file
Range('Sheet1', 'C3').value = random.randint(0,10)
updateValue = Range('Sheet1', 'C3').value
print("updatedValue=" , updateValue);
create_file()
if __name__ == '__main__':
path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'FirstExcel.xlsm'))
Workbook.set_mock_caller(path)
my_macro()
当我在 Eclipse 中 运行 以上代码时,它会创建一个文件并更新 excel 电子表格。但是,当我从 excel 运行 它更新电子表格时,它不会创建文件。
问题是 Excel 当前在与从 Python 调用文件时不同的工作目录中启动 Python 解释器。这是 GitHub 上的未决问题,请参阅 here。
同时,只需为 open
和 write
中的所有文件使用 absolute/full 路径。您还应该能够使用 os.path.abspath(os.path.join(os.path.dirname(__file__), 'testFile.txt'))