I want to insert current date into name of new layer. My current code to save layer with hardcoded name is like this:
_writer = QgsVectorFileWriter.writeAsVectorFormat(layer,r"D:\Maps\layer.shp","utf-8",None,"ESRI Shapefile")
I can get current date using:
cur_date_apndx = time.strftime("%d_%m_%Y")
statement, but I can not insert cur_date_apndx into the code above. I think "r" in the 2nd parameter of writeAsVectorFormat
is the reason. If I remove "r" layer is not saved.
Could anyone help?
2 Answers 2
I prefer just using forward slashes instead of using raw string coupled with backward slashes. But you could use the format()
method to insert the date into the filename:
_writer = QgsVectorFileWriter.writeAsVectorFormat(layer, "D:/Maps/layer_{}.shp".format(cur_date_apndx),"utf-8",None,"ESRI Shapefile")
-
112 seconds between the two answers :)mgri– mgri2017年06月06日 10:34:40 +00:00Commented Jun 6, 2017 at 10:34
-
@mgri - Indeed! And
cur_date_apndx
does come out as a string :)Joseph– Joseph2017年06月06日 10:37:02 +00:00Commented Jun 6, 2017 at 10:37 -
@Joseph, perfect! But _writer = QgsVectorFileWriter.writeAsVectorFormat(layer, "D:/Maps/layer_{}.shp".format(cur_date_apndx),"utf-8",None,"ESRI Shapefile") doesn`t work and _writer = QgsVectorFileWriter.writeAsVectorFormat(layer, r"D:/Maps/layer_{}.shp".format(cur_date_apndx),"utf-8",None,"ESRI Shapefile") is working.E Bobrov– E Bobrov2017年06月06日 11:15:27 +00:00Commented Jun 6, 2017 at 11:15
-
1@EBobrov - Most welcome although mgri's answer is also correct (and he answered first) so perhaps accept his answer as both our solutions are essentially the same? ;)Joseph– Joseph2017年06月06日 11:18:08 +00:00Commented Jun 6, 2017 at 11:18
-
@Joseph - I do not know why but mgri`s answer (without r) is not working. Previously I tried hardcoded layer name without variable and r method but unsuccessfully.E Bobrov– E Bobrov2017年06月06日 11:25:56 +00:00Commented Jun 6, 2017 at 11:25
I can't test it right now, but if cur_date_apndx
is a string, you may simply compose the output name in this way:
output_name = 'D:/Maps/layer_' + cur_date_apndx + '.shp'
_writer = QgsVectorFileWriter.writeAsVectorFormat(layer,output_name,"utf-8",None,"ESRI Shapefile")
otherwise, use str(cur_date_apndx)
isntead of cur_date_apndx
.
I used slashes (/
) instead of backslashes (\
) because your format time was "%d_%m_%Y"
(but the method with r
should however work).
-
Thank you! It is strange but statement without 'r' doesn
t work. I
ve commented it above.E Bobrov– E Bobrov2017年06月06日 11:19:22 +00:00Commented Jun 6, 2017 at 11:19 -
@EBobrov weird behavior, maybe I'm missing something. Did you try using double quotes?mgri– mgri2017年06月06日 12:39:29 +00:00Commented Jun 6, 2017 at 12:39
-
yap, I tried to use double quotes.E Bobrov– E Bobrov2017年06月07日 14:48:54 +00:00Commented Jun 7, 2017 at 14:48