So I have a XLS file that is being accessed via the xlutils library. When my program is finished doing its process, its supposed to delete the original file and rename the temporary file to the original file. The data in the excel file is being input a website and data from the website is being extracted and then written to the excel sheet. All this is fine, however, when its done its having an issue renaming the temp file.
The temp file is simply a copy made via the following function:
def rename(self, fpath):
tempf=os.path.splitext(fpath)[0]
tempf=tempf + "-output" + ".xls"
shutil.copyfile(fpath,tempf)
return tempf
I have created a function which is called when the for loop for inputting data and extracting is finished:
def allDone(self, event):
dlg = wx.MessageBox("All done!", "Ask Alfred", wx.OK | wx.ICON_INFORMATION)
os.unlink(self.fpath)
os.rename(self.temp, self.fpath)
Using Process Explorer, it shows that the temp file is still open in python.exe. I don't know how to close the file and free memory since it is being opened by using:
rbook=open_workbook(file)
sheet = rbook.sheet_by_index(0)
where file will simply be replaced with whatever self.temp is.
When a GO button is pushed the following happens:
def onGo(self, event):
fpath=self.pathBox
fpath=fpath.GetValue()
self.fpath=fpath
temp=myClass.rename(fpath)
self.temp=temp
openFile(temp)
def rename(self, fpath):
tempf=os.path.splitext(fpath)[0]
tempf=tempf + ".alf"
shutil.copyfile(fpath,tempf)
return tempf
So the name of the file which is in a SearchCtrl called "pathBox" is obtained and a temp copy is made and then renamed.
Related
I've made a custom operator for saving the current .blend file to a network drive. This yields about 20% performance boost compared to the default blender save function. First the .blend file is saved to the local temp directory and then moved over to the network drive.
Here is my code:
class toolbox_OP_SaveToNetwork(Operator):
bl_idname = 'toolbox.save_to_network'
bl_label = 'Save'
bl_description = "Save file locally and copy it to it's network path"
def execute(self, context):
if(bpy.data.is_saved == False):
return {"FINISHED"}
# return bpy.ops.toolbox.save_as_to_network("INVOKE_DEFAULT")
print("Save locally, copy to network drive...")
filename = bpy.path.basename(bpy.data.filepath)
tmp_filepath = os.path.join(tempfile.gettempdir(), filename)
report = bpy.ops.wm.save_as_mainfile(filepath=tmp_filepath, check_existing=False, copy=True)
if report == {"FINISHED"}:
# shutil seems to be slower than native os move
# shutil.move(tmp_filepath, bpy.data.filepath)
os.system('move %s %s' % (tmp_filepath, bpy.data.filepath))
return {"FINISHED"}
else:
return report
I would also like to implement the Save As functionality. This is helpful if I don't want to save by overriding my current file but rather incrementing it's version.
Now here is my problem:
Let's say I have test01.blend and want to save as test02.blend
If i use my script, then after saving the file the test01.blend file would still be opened in blender, because I have to use the copy=True argument in the bpy.ops.wm.save_as_mainfile operator. (This has to be used so blender does not open the .blend file which get saved in the local temp directory)
Is it somehow possible to change the filepath of the current opened .blend file via the python API without opening/loading a new file?
After the operation bpy.data.filepath should the point to path/to/file/test02.blend instead of path/to/file/test01.blend
I have a piece of code which would save a file and after once clicked the tkinter button for saving it, python saves it every 5 minutes. But you could also open the saved file: so I need a piece of code which first tries to close the file (if open) and then save it again. This is my code:
def save_changes():
# first close the saved_file
wb.save(saved_file)
cur_time = datetime.datetime.now().strftime("%H.%M.%S")
saved_label.config(text="laatst opgeslagen op:\n" + cur_time)
saved_label.after(300000, save_changes)
my code is uploading a txt file to my drop box, but the document it self is empty of content. It only reading inside the title of the file 'test_data.txt', the data itself which is in the real file is not there. The file never updates either when running the script a second time, but I suspect this is because the file is not being updated (it's not actually reading the contents of the .txt file). If anyone could help me with this I would appreciate it.
import dropbox
from dropbox.files import WriteMode
overwrite = WriteMode('overwrite', None)
token = 'xxxx'
dbx = dropbox.Dropbox(token)
dbx.users_get_current_account()
dbx.files_upload('test_data.txt', '/test_data.txt', mode = WriteMode('overwrite'))
files_upload should recieve a content to upload. In your current code you are asking to upload string "test_data.txt" as file "/test_data.txt".
with open('test_data.txt', 'rb') as fh:
dbx.files_upload(fh.read(), '/test_data.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()
When I run the above code in Eclipse, it creates a file and updates the excel spreadsheet. However, when I run it from excel it updates the spreadsheet, but does not create a file.
The issue is that Excel currently starts the Python interpreter in a different working directory than when you call the file from Python. It's an open issue on GitHub, see here.
In the meantime, just use an absolute/full path for all your files in open and write. You should also be able to use something like os.path.abspath(os.path.join(os.path.dirname(__file__), 'testFile.txt'))
The link to the code is here (didn´t copy it here to give the guy credit):
I don´t want it to change the name with the date as is currently doing, but to download the file "finviz.csv" and rewrite it each day (with the scheduler task) to keep the data updated in my data system.
I´ve tried some tweaks, but I´m no developer I don´t have a clue how to do it.
Can you please help?
The comments in the code described it quite clearly:
# we're going to name the file by the date it was downloaded (e.g. 2012-3-18.csv)
fname = now.strftime("%Y-%m-%d")+".csv";
So just change the line to
fname = "finviz.csv";
And fix the file existence check logic:
# check if the file does not already exist
if not os.path.isfile(savepath+"/"+fname):
# open a file to save the data to ("wb" means write binary mode)
outfile = open(savepath+"/"+fname, "wb");
# download the data from the url specified above
infile = urllib2.urlopen(url);
# read the downloaded data and write it to our output file
outfile.write(infile.read());
# close the output file once we're done
outfile.close();
else:
print "'"+fname+"' ALREADY EXISTS in the save directory '"+savepath+"'.";
to:
# open a file to save the data to ("wb" means write binary mode)
outfile = open(savepath+"/"+fname, "wb");
# download the data from the url specified above
infile = urllib2.urlopen(url);
# read the downloaded data and write it to our output file
outfile.write(infile.read());
# close the output file once we're done
outfile.close();
You have to change the line
fname = now.strftime("%Y-%m-%d")+".csv";
for
fname = "finviz.csv";
And you also need to delete this if (and its corresponding else):
if not os.path.isfile(savepath+"/"+fname):