-
Notifications
You must be signed in to change notification settings - Fork 0
/
python.csv
We can make this file beautiful and searchable if this error is corrected: Illegal quoting in line 6.
2973 lines (2927 loc) · 198 KB
/
python.csv
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Import python module;import math;python
Import specific function of a module;from math import ceil;python
Import a module with abbreviation;import numpy as np;python
When directly called - programm is running from here;if __name__ == '__main__':;python
Check which python version is installed;python --version;python
Use modules / functions from other folder;"import sys, os
sys.path.append(os.path.join('C:/', 'Users\path_to_module')) # Create Path to module
import RapidTechTools as rtt # Import Module RapidTechTools";python
Install virtualenv;pip install virtualenv;python
Global packages installed;pip list;python
Shows where the python-file is (Windows);where python;python
Shows where the python-file is (Linux);which python;python
Create new virtual environment env;python -m virtualenv env;python
Create new virtual environment env (for python3 eg. on MacOS);python3 -m venv env;python
Extracts all the modules / dependencies to a txt-file;pip freeze --local > requirements.txt;python
Go back to the global environment;deactivate;python
Create new virtual env with specific python-version;virtualenv -p C:\..path to..\Python37\python.exe py37_env;python
Activate new virtual env named py37_env;py37_env\Scripts\activate;python
Shows the used python version in the virtual env;python --version;python
Install all the packages from requirements.txt;pip install -r requirements.txt;python
Windows: Show all installed python-versions + paths;py -0p;python
Activate environment;"venv\Scripts\activate
when activated: pip list # Now only shows the installed modules for the virtual environment
pip install package # Only installs in the activated virtual environment";python
install virtual environment with specific python-version;"download and install the python-version - Important: remember the path to the python.exe
create a venv with: virtualenv envName -p path\to\new_python.exe";python
install module;pip install moduleXY;python
upgrade module;pip install moduleXY --upgrade;python
Install specific version;pip install -Iv pyinstaller==4.8;python
uninstall module XY;pip uninstall module XY;python
show installed modules in actual environment;pip list;python
output modules in requirements.txt;pip freeze > requirements.txt;python
install modules from requirements.txt;pip install -r requirements.txt;python
Installation;pip install pyinstaller;python
Install specific version;pip install -Iv pyinstaller==4.8;python
Generate the bundle in a subdirectory called dist.;pyinstaller prg.py;python
Generate only one file;pyinstaller --onefile prg.py;python
Generate only one file (to get for sure the pyinstaller from the actual env);python -m Pyinstaller --onefile prg.py;python
Collect data for specific python module;--collect-data moduleXY;python
add this when some modules are not found;--copy-metadata pandas_ta;python
When some modules are making problems - sometimes this helps;--hidden-import=pymssql;python
<frozen importlib._bootstrap> error when using yfinance;pyinstaller --onefile --collect-data frozendict stockma3.py;python
when there is a depreciating warning from matlib;--exclude-module matplotlib;python
Generate file with icon;--icon=app.ico;python
Generating under mac os sometimes only work with this params;--hidden-import=pkg_resources.py2_warn;python
Generating under mac os sometimes only work with this params;--hidden-import=cmath;python
Open this file to start the python-program;prg.exe;python
only working with import yfinance (not with import yfinance as yf);yfinance module;python
Problems with some added python modules (eg. pycountry);"https://groups.google.com/g/pyinstaller/c/OYhJdeZ9010/m/32g3-T8XBAAJ
Create hook-file hook-pycountry.py with content:
from PyInstaller.utils.hooks import copy_metadata, collect_data_files
datas = copy_metadata(""pycountry"") + collect_data_files(""pycountry"")
Compile Program with
pyinstaller --onefile --exclude-module matplotlib --additional-hooks-dir=. TestPyCountry.py";python
Problems with path when executing from py and exe;config_name = 'creds.json' # Define the config file name;python
Determine if application is a script file or frozen exe;"if getattr(sys, 'frozen', False): # Get path when starting as executable
application_path = os.path.dirname(sys.executable)
elif __file__: # Get path when running from IDE as py-file
application_path = os.path.dirname(__file__)
config_path = os.path.join(application_path, config_name) # Final Config Path";python
Using Inno Setup Compiler for creating a setup.exe for all files;"https://jrsoftware.org/isdl.php
- Application Information => provide application informations (appName, appVersion, publisher, website)
- Application Files => select application main executable file and add all necessary folder and files
- Application File Association => no selection
- Application Documentation => select files which should be shown before / after the installation
- Setup Languages => select which languages should be included during installation
- Save installation script
- Final setup.exe is stored in the ""Output""-folder";python
"Comment / Uncomment selected lines (""/"" on numblock) (commenting in VS Code)";Ctrl K Ctrl C;python
"Comment / Uncomment selected lines (""/"" on numblock) (commenting in VS Code)";Ctrl K Ctrl U;python
Find in File;Ctrl F;python
Replace in File;Ctrl H;python
Selects whole line;Ctrl L;python
Search in all files;Ctrl Shift F;python
Replace in Path (in all Files);Ctrl Shift H;python
Jump to this Grouping Window;Ctrl 1/2/3;python
Find next;F3;python
Goto line;Ctrl G;python
Copy / Duplicate lines;Shift Alt Up/Down;python
Expand / Shrink selection;Shift Alt Left/Rigth;python
Move line;Alt Up/Down;python
Suggestions for fix error, function informations;Alt Enter;python
Open the project windows (on the left side);Alt 1;python
Show usage of the variable, function, class;Alt F7;python
Focus back on the editor window;Esc;python
Collapse everything;Ctrl K Ctrl 0;python
Expands everything;Ctrl K Ctrl J;python
"Collapse block (""-"" on numblock)";Ctrl K Ctrl L;python
"Expand block (""+"" on numblock)";Ctrl K Ctrl L;python
Select whole file;Ctrl A;python
Undo (backwards) / Redo (forwards);Ctrl (Shift) Z;python
Select word to the beginning;Ctrl Shift Left;python
Select word to the end;Ctrl Shift Right;python
Go one word left;Ctrl Left / Right;python
Delete current line;Ctrl Shift K;python
Delete to end of word;Ctrl Del;python
Delete to beginning of word;Ctrl Background;python
Hide/Show sidebar;Ctrl B;python
Hide/Show terminal;Ctrl J;python
Show command line (eg. open a file where the name is known);Ctrl P;python
Open the the command panel;Ctrl Shift P;python
Toggle through the open files in the editor;Ctrl TAB;python
Close File;Ctrl WARNING;python
MultiCursor - Select more cursors in rows for multiple change in rows;Ctrl Alt Up/Down;python
MultiCursor - Select Cursor at multiple positions for the same name;Ctrl D;python
Select all occurences of this word in the document and change all with one change;Ctrl Shift L;python
Select whole word;Ctrl D;python
Jump to the function definition;Ctrl Click;python
Close Tab;Ctrl W;python
Show suggestions for the actual code function / method;Ctrl Space;python
https://www.shortcutfoo.com/app/dojos/intellij-idea-win/cheatsheet;"Ctrl / # Comment / Uncomment selected lines (""/"" on numblock) (commenting in VS Code)
Ctrl / # Comment / Uncomment selected lines (""/"" on numblock) (commenting in VS Code)
Ctrl Alt F7 # Find usages
Ctrl F # Find in File
Ctrl R # Replace in File
Ctrl Shift R # Replace in Path (in all Files)
F2 # jump to the next error
F3 # Find next
Ctrl G # Goto line
Ctrl D # Copy / Duplicate lines
Ctrl X # Cut line (when nothing selected)
Ctrl C # Copy line (when nothing selected)
Alt Shift Down/Up # Move line
Ctrl E # Recent opened files
Ctrl TAB # Switch windows in IDE
Ctrl (Shift) W # Select / deselect parts of the code step by step
Alt Enter # Suggestions for fix error, function informations
Alt 1 # Open the project windows (on the left side)
Alt F7 # Show usage of the variable, function, class
Esc # Focus back on the editor window
Ctrl Shift - # Collapse everything
Ctrl Shift + # Exapnds everything
Ctrl - # Collapse block (""-"" on numblock)
Ctrl + # Expand block (""+"" on numblock)
Ctrl A # Select whole file
Ctrl (Shift) Z # Undo (backwards) / Redo (forwards)
Ctrl Shift Left # Select word to the beginning
Ctrl Shift Right # Select word to the end
Ctrl Left / Right # Go one word left
Ctrl Y # Delete current line
Ctrl Del # Delete to end of word
Ctrl Backspace # Delete to beginning of word
lorem + TAB # Create lorem text for html-code
p>lorem + TAB # Create lorem text inside <p>-tags";python
https://www.makeuseof.com/tag/google-chrome-shortcuts-pdf/;"F5 # Refresh site
Ctrl Tab # Go tab right
Ctrl Shift Tab # Go tab left
Ctrl F5 # Clear Cache and reload page";python
https://fossbytes.com/windows-keyboard-shortcuts-cheat-sheet-for-windows-10/;"Alt Tab # Focus on other window
Ctrl C # Copy
Ctrl X # Cut
Ctrl VALUES # Paste";python
Enable pushing with ssh-key in Idea and VSCode;"Enable open ssh agent: https://dev.to/aka_anoop/how-to-enable-openssh-agent-to-access-your-github-repositories-on-windows-powershell-1ab8
Run commands: https://stackoverflow.com/questions/56490194/vs-code-bitbucket-ssh-permission-denied-publickey";python
Import module for math calculations;import math;python
Import module for reading arguments from the command line;import sys;python
Using some numpy functions;import statistics as stat;python
Result without Decimals (=> 2);5 // 2;python
Modulo / Rest of the division (=> 1);7 % 2;python
Assigment of several varaibles;d,e,f = 4,5,6;python
Change / swap 2 values;a,b = b,a;python
Increase value by one;a += 1;python
"For better readability - ""_"" are possible using long num-values (will be ignored)";i = 1_000_000;python
Value is rounded to two decimal places => 77.23;round (77.2321, 2);python
Round to tens place;int(v - v%10);python
Conversion to String / Float / Int;"str(5), float(""5""), int(""5"")";python
Outputs absolute value => 2;abs(-2);python
Wait for pressing ENTER (or a keyboard stroke) to follow along;"input(""ENTER to continue"")";python
Input age and change to int;"int(input(""Alter?""))";python
Returns the type of a variable;type(var);python
Shows all available methods and attributes for the object as list;dir(var);python
Check if x has type format float (others: str,int,list,tuple,range,dict,set,bool);isinstance(x,float);python
Set var to max-value (float infinite);"x = float(""inf"")";python
Calculates the sqrt of the value => i3;math.sqrt(9);python
Check if a variable exists;"if ""myVar"" in locals():";python
Check for argument which is given when starting the program;sys.argv[1:].upper();python
"Print ""Text"" (with a linebreak \n at the end)";"print(""Text"")";python
Print with end-statement (next print will be in the same line;"print(""Text"", end=""-"")";python
Print text with linebreaks \n etc;"print(repr(""xyz\n""))";python
python test.py arg1 arg2 arg3;example starting program;python
Show the arguments from the command line when starting the program eg. ['test.py', 'arg1', 'arg2', 'arg3'];str(sys.argv);python
Len of the arguments - eg. 4 (program test.py itself and 3 arguments following);len(sys.argv);python
Find the minimum value => 3;min(3,5,7);python
Find the maximum value => 7;max(3,5,7);python
Find the mean value => 5 (with statistic-module - input must be given as list);stat.mean([3,5,7]);python
Stop program at this point (helpful in test-situations);exit();python
Calculate the change from an old value to a new value in percent;(newVal-oldVal)/oldVal * 100;python
Import pretty print functionality;import pprint as pp;python
pretty print dict line by line;pp.pprint(dict);python
pretty print with max line-length 30;pp.pprint(dict, width=30);python
pretty print only level 1 of nested list eg. ['level1', [...]];pp.pprint(nestedList,depth=1);python
pretty print only level 2 of nested list eg. ['level1', ['level2', [...]]];pp.pprint(nestedList,depth=2);python
convert binary value to decimal;"int(""1010"",2)";python
Import random module - fast, but not very secure;import random;python
Random int number between 1 and 6 like a cube;random.randint(1,6);python
Random float number between 1 and 3;random.uniform(1,3);python
Random value between 0 and 1 in float format - eg. 0.16394553;random.random();python
Random float in the range from 1 to 10;random.uniform(1,10);python
Random value for standard deviation;random.normal(0,1);python
Choose random entry from a list;random.choice(list);python
Choose 3 random (unique) entries from the list;random.sample(list,3);python
Choose 3 random entries from the list (possible to be the same);random.choices(list,k=3);python
Shuffle the content of a list;random.shuffle(l);python
Can reproduce the same results (unsecure);random.seed(1);python
generate a random uppercase 6-char string;""""".join(random.choices(string.ascii_uppercase, k=6))";python
Import secrets module - for security reasons (is slower);import secrets;python
Random int in the range from 0-10 (10 excluded);secrets.randbelow(10);python
Random int with 4 bits (highest possible value is 15 - 1111);secrets.randbits(4);python
Random choice (which is not reproducable);secrets.choice(l);python
Define string over more lines in editor with;"s = '''this \
and this'''";python
first char of a string;c = s[0];python
last char of a string;c = s[-1];python
Insert variable in string oldest method (%s for string, %i for int, %f for float, %.2f for 2 decimals);"s = ""text %s bla"" % var";python
Insert variable in string old method (:.2f for 2 decimals);"s = ""text {} bla"".format(var)";python
Insert variable in string new method;"s = f""text {var} bla""";python
Format int with allways 2 digits;"s = f""{var:02d}""";python
Format float with allways 2 decimal places;"s = f""{float:0.2f}";python
Format float with 2 decmial places and overall 9 chars with leading 0;"s = f""{float:09.2f}";python
Multiple use;"""{0} like, {0} especially {0} but {1}"".format(""Joe"", ""noodles"")";python
Returns the index where the text is found;"s.find (""ist"")";python
Counts the occurrence of a text;"s.count (""i"")";python
Counts several chars in a text;re.findall('[.,’]', s);python
"Return all index of the char ""/"" in the string";"[i for i, c in enumerate(s) if c == ""/""]";python
Returns all index as a list (needs import re);[x.start() for x in re.finditer('ist', s)];python
Lowercase the whole string;s = s.lower();python
Capitalize the whole string;s = s.upper();python
Capitalize the first char;s = s.capitalize();python
Capitalize the first char of all words;s = s.title();python
"Check if string is starting with char ""H""";"s.startswith(""H"")";python
Check if string starts with several chars;"s.startswith((""H"",""F"",""L""))";python
"Check if string is ending with char ""H""";"s.endswith(""H"")";python
Check if string ends with several chars;"s.endwith((""H"",""F"",""L""))";python
"Split the words in a list which are seperated by "" """;"s.split("" "")";python
"Split for several chars (eg. "" "" and ""\n"" and "" ,"")";"re.split("" |\n| ,"", s)";python
"', 1)[0] => Split till the first occurence of ""=>""";s.split(';python
Split sentences after line breaks;s.splitlines();python
Delete all whitespaces at the beginning and the end;s = s.strip();python
Remove all duplicate spaces in a string;"s = "" "".join(s.split())";python
Replacement of two strings;"s = s.replace(""e"",""X"")";python
Replace several chars in a string;"s = re.sub(""[e0fi]"", ""X"", s)";python
Replace several chars in a string (get back a tupple: 1st changed string, 2nd: count of changed chars);"s = re.subn(""[e0fi]"", ""X"", s)";python
True if the whole string are digits;s.isdigit();python
True if the whole string are no digits;s.isalpha();python
TRUE if string2 is in strings1;s2 in s;python
Change string to list with all single chars;l = list(s);python
Convert char to ASCII value;ord(char);python
Convert ASCII value to char (eg. 65=A, 97=a);chr(ascii);python
Outputs hashvalue oif the string (needs import hashlib);hashlib.md5(s).encode('utf-8')).hexdigest();python
Execute statement in a string => hello;"exec(print(""hello""))";python
Gives the value of an expression => 4 (dangerous - can used for sql-injections);"eval(""2+2"")";python
Reverse a string;my_string[::-1];python
Print string with special characters;repr(s);python
check if any string is in another string or all strings are in another string;"s = ""A string is more than its parts!""
l = [""more"", ""blabla"", ""nothing""]
if any(x in s for x in l): # check if any elems from checks in string s
if not any(x in s for x in l): # check if any elems from checks are NOT in string s
if all(x in s for x in l): # check if all elems from checks are in string s";python
import regex module;import re;python
Information about regex handling;https://medium.com/factory-mind/regex-tutorial-a-simple-cheatsheet-by-examples-649dc1c3f285;python
test regex strings;https://regex101.com/;python
"Find str with 4xdigits + ""-""char + 2xdigits";"pattern = re.compile(""^[0-9]{4}-[0-9]{2}$"")";python
Check if pattern matches - <> None when matches;pattern.match(s);python
"Find str with 4xdigits + ""-""char + 2xdigits";"pattern2 = re.compile(""[0-9]{4}-[0-9]{2}"")";python
"Find str with 3 to 4 xdigits + ""-""char + 2xdigits";"pattern2 = re.compile(""[0-9]{3,4}-[0-9]{2}"")";python
Check with fullmatch (^ and $ not necessary) - <> None when matches;pattern.fullmatch(s);python
"Char ""."" has to cherck with ""\n"" (is a wildcard letter in regex)";"pattern3 = re.compile (""[0-9]{1}\.[0-9]{3}"")";python
Replace all digits in string with blank;"re.sub(""\d"","""",s)";python
"Insert blank before every capitalized word eg. ""CostOfRevenue"" => ""Cost Of Revenue""";"re.sub(r'([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))', r'\1 ', ""txt"")";python
count all words which start and ends with a char from cL;"len(re.findall(f'[{cL}""]{w}[{cL}""]', l))";python
count all words which start with w and ends with a char from cL;"len(re.findall(f'^{w}[{charList}""]', l))";python
count all words which start with a char from cL and ends w;"len(re.findall(f'[{charList}""]{w}$', l))";python
count all words which have w in the middle of anything else;len(re.findall(f'(.*?){w}(.*?)', l));python
"Define pattern => as many digits (endless) + "" "" + one lowercase cahr + "":"" + as many digits (endless)";"pattern = ""([0-9]+) ([a-z]:([a-z]+)""";python
"Check if elem fits the pattern => returns <re.Match object; span=(0, 19), match=""3 n: nnnlncrnnnnn"">";match = re.search(pattern, elem);python
Assign the value of the first group => 3;value = match.group(1);python
"Show the full string => ""3 n: nnnlncrnnnnn""";all = match.group(0);python
Define several empty lists (NOT use l1=l=l3=[] => this would be the SAME list);l1,l2,l3,l4 = ([] for i in range(4));python
check for True if list has an element;if l;python
check for False if list is empty (same would be if l == [];if not l;python
Define list with content;l = [4,5,6];python
Define list - content is list from 0 to 19;l = list(range(20));python
Define list with 8 empyt strings;"l = ["""" for x in range(8)]";python
Uppercase the whole list;l = [x.upper(for x in l)];python
Define a nested list with 5x5;"l = [["""" for x in range(5)] for x in range(5)]";python
Add both lists together (to a new list);l1 + l2;python
Add 1 element to the list at the back;l.append(1);python
Add several elements to the list at the back;l.extend([6,5,4]);python
Insert an element at the index-position 3;"l.insert(3, ""xyz"")";python
"Returns first index position of element ""xyz""";"l.index(""xzy"")";python
Delete last element from list;l.pop();python
Delete first element from list;l.pop(0);python
Sort list ascending;l.sort();python
Sort list descending;l.sort(reverse=True);python
Sort list and store it in a different independent list;l_sort = sorted(l);python
Sort list descending and store it in a different independent list;l_sort = sorted(l, reverse=True);python
Sort the same way as the operating system (need: from natsort import os_sorted);l_sort = os_sorted(l);python
Check if a list is sorted (by ascending);if sorted(l) == l;python
Check if a list is sorted by descending;if sorted(l, reverse=True) == l;python
Sort list by len of elements;l.sort(key=len);python
Define nested list;l = [[1,4,3], [2,2,4], [3,1,5]];python
Sort nested list for the 2nd element ascending;l.sort(key=lambda x: x[1]);python
Sort nested list for the 2nd element descending;l.sort(key=lambda x: x[1], reverse=True);python
Sort nested list 1st for the 1st elem, then for the 2nd elem;l.sort(key=lambda x: (x[0], x[1]));python
Sort nested list 1st for the 1st elem, then for the 2nd elem descending;l.sort(key=lambda x: (x[0], x[1]), reverse=True);python
Reverse the complete list;l.reverse();python
Reverse complete list and store it in different independent list;l_reverse = list(reversed(l));python
Delete element at index position 2;del l[2];python
Delete first element with this value from the list;"l.remove(""abc"")";python
Delete complete content of the list (same as l = []);l.clear();python
Find smallest element in the list;min(l);python
Find greatest element in the list;max(l);python
Find longest string in the list;max(mylist, key=len);python
Find lenght of longest string in the list;len(max(mylist, key=len));python
Sum of all elements in the list;sum(l);python
Pair Sorting from 2 lists (1 with 1, 2 with 2, 3 mit 3, aso.);2xls_sum = [sum(pair) for pair in zip(l1, l2)];python
Count of elements in list;len(l);python
"Count of occurence of the element ""a"" in the list";"l.count(""a"")";python
No seperate copy of the list (updates in both lists);l2 = l1;python
Separate individual copy of the list (no updates in both lists);l2 = l.copy();python
Separate individual copy of the list - 2nd variant;l2 = l[:];python
Separate individual copy of the list - 3rd variant;l2 = list(l);python
Seperate copying a nested list - import copy necessary;l2 = copy.deepcopy(l);python
First element;l[0];python
Last element;l[-1];python
Last 3 elements;l[-3:];python
Elements from index position 2 to 3;l[2:4];python
Elements from 0 to 1 (exclusive index position 2);l[:2];python
Elements from index position 2 to the end of the list;l[2:];python
Every second element [start:end:step];l[::2];python
Check if element is in list;9 in l;python
Check if any elements from the list are in the string;"if any(x in st for x in [""ab"",""cd"",""de""]):";python
Check if all elements from the list are in the string;"if all(x in st for x in [""ab"",""cd"",""de""]):";python
Check if all elements from the list are NOT in the string;"if all(x not in str for x in [""ab"",""cd""]):";python
Iterate through list content;for i in l:;python
Iterate through list with index;for i in range(len(l)):;python
Iterate through list with index and content;for idx, cont in enumerate(l):;python
Iterate through 2 lists pair-wise (stops when the shorter list is reached);for x,y in zip(l1,l2):;python
"Create string with elements joined together with "", "" eg. [""a"",""b"",""c""] => a, b, c";', '.join(l);python
Define list;a = [1,2,3,4,5];python
List is mapped with the lambda function => [2,4,6,8,10];list(map(lambda x: x*2, [1,2,3,4,5]));python
Also possible with list comprehension => [2,4,6,8,10];l=[x*2 for x in l];python
Also possible with list comprehension => [2,4];l=[x for x in l if x%2==0];python
List comprehension with if and else;l=[x*2 if x.isdigit() else x for x in l];python
List is filtered with lambda for even numbers => [2,4];list(filter(lambda x: x%2==0, [1,2,3,4,5]));python
Build paris as tuple => (1,4),(2,5),(3,6);zip([1,2,3],[4,5,6]);python
Remove duplicates from a list;list(set(l));python
Remove duplicates from a list and keep existing order;list(dict.fromkeys(l));python
Change elements in list to int;list(map(int,l));python
Transpose nested list (change rows and columns);[[x[i] for x in l] for i in range(len(l[0]))];python
rotate list for n places;"def rotate(l, n):
return l[-n:] + l[:-n]";python
Iterate over 2 lists at the same time using zip;"animal = ['Cat', 'Dog', 'Fish', 'Goat']
age = [1, 2, 2, 6]
z = zip(animal, age)
for animal, age in z: ...";python
Adjust nested list to the same length;"maxLen = max(map(len, l))
for row in l:
while len(row) < maxLen:
row.append(None)";python
Create a tuple;t = (4,5,6);python
Create a tuple from a list;t = tuple([3,4,4];python
Selection / slicing of elements - same as with lists;t[];python
Change tuple to list;l = list(t);python
Change list to tuples;t = tuple(l);python
Assigning vars to tuple-elements (a=0, b=1, c=2);a,b,c = (0,1,2);python
Assigning to tuple-values (f=0, m=[1,2,3], l=4);f,*m,l = (0,1,2,3,4);python
Define empty dict;d = {};python
Define dict with content;"d = {""one"": 1, ""two"": 2, ""three"": 3}";python
2nd way to defince a dict with content;d = dict(one=1,two=2,three=3);python
Define dict with content (with dupels);"d = dict([(""one"",1),(""two"",2),(""three"",3)])";python
Define dict with content (with pairs in nested list);"d = dict([[""one"",1],[""two"",2],[""three"",3]])";python
Define dict with 2 different lists (1x keys and 1x values);"d = dict(zip([""one"",""two"",""three""], [1,2,3]))";python
Access value with key element (error when the key is not in the dict);"d[""two""]";python
BETTER: Acesss value with get for key element (no error when the key is not in the dict - returns second parameter instead);"d.get(""two"",""N/A"")";python
Access value - same as get - but also initialize the key when it is not in the dict - with the second parameter);"d.setdefault(""two"",""N/A"")";python
Find key for specific value (v) in dict;key = list(d.keys())[list(d.values()).index(v)];python
Read keys from dict to list;list(d.keys());python
Read values from dict to list;list(d.values());python
Count of entries in dict;len(d);python
Check if key is in dict (true / false);"""three"" in d";python
"New entry for dict (key = ""four"", value = 4)";"d[""four""] = 4";python
Delete specific key in dict;"del d[""one""]";python
Rename dict-keyname;mydict[new_key] = mydict.pop(old_key);python
Combine 2 dicts (if key is in both dicts - the second value will be taken);combined_dict = {**d1, **d2};python
Check if key is in dict;"if ""xyz"" in d:";python
Copying a dict (all changes will be made in BOTH dicts);d2 = d;python
Copying a dict (NOT WORKING with nested lists in the dict - use deepcopy!);d2 = d.copy();python
Copying a dict (NOT WORKING with nested lists in the dict - use deepcopy!);d2 = dict(d);python
Copying a dict (dicts will be handled seperate) - import copy necessary;d2 = copy.deepcopy(d);python
Dict d get updated with d2 (all existing keys are overwritten - and new added);d.update(d2);python
Iterate through dict keys;for key in d.keys():;python
Iterate through sorted dict keys ascending;for key in sorted(d.keys()):;python
Iterate through sorted dict keys descending;for key in sorted(d.keys(),reverse=True):;python
Iterate through dict values;for val in d.values():;python
Iterate through keys and values of the dict;for key, val in d.items():;python
built dict with dict-comprehension;d = {x[0]: x[1:] for x in l};python
Sort dict descending according to values (=item[1]);d = {k: v for k, v in sorted(d.items(), key=lambda item: item[1], reverse=True)};python
Sort dict ascending according to keys (=item[0]);d = {k: v for k, v in sorted(d.items(), key=lambda item: item[0])};python
Dict sorted: 1st value-desc (x[0]) - 2nd key-ascnd (-x[0]);d = {k: v for k, v in sorted(d.items(), key=lambda x: (-x[1],x[0]))};python
Sort dict and output list, sorted according to the 3rd element of the list in the dict;l = sorted(d.items(), key=lambda e: e[1][2]);python
Sort dict and output list, sorted according to the 3rd element of the list in the dict - descending;l = sorted(d.items(), key=lambda e: e[1][2], reverse=True);python
Merge 2 dictionaries;d3 = {key: d1.get(key,0)+d2.get(key,0) for key in set(d1)|set(d2)};python
save dict to pkl-file;"import pickle
with open(""fn.pkl"", ""wb"") as f:
pickle.dump(dict, f)";python
read dict from pkl-file;"import pickle
with open('fn.pkl', 'rb') as f:
d = pickle.load(f)";python
Define empty set - {} would define a dict and not a set;s=set();python
Define set with content;s = {1,1,2,2,3,4};python
"Define empty set - returns: {""o"",""l"",""H"",""e""}";"s = set(""Hello"")";python
Define second set;s2 = {1,7,8};python
Add element in set1;s.add(5);python
Add several elements to set1;s.update([10,11,12]);python
Intersection of 2 sets (same as: s.intersection(s2));s & s2;python
Untion of 2 sets (same as: s.union(s2));s | s2;python
Difference of 2 sets (same as: s.difference(s2));s - s2;python
True if s is subset from s2 (same as: s.issubset(s2));s <= s2;python
Check if element is in set;3 in s;python
Clear the set;s.clear();python
Delete lowest elmeent in set;s.pop();python
Delete element 5 from set - but key error possible;s.remove(5);python
Delete element 5 from set - NO key error possible;s.discard(5);python
Iterate through set content;for i in s:;python
Copying a set (all changes will be made in BOTH sets);s2 = s1;python
Copying a set (set will be handled seperate);s2 = s.copy();python
Copying a set 2nd method (set will be handled seperate);s2 = set(s);python
Define a frozenset - no changes are possible in the set - union, intersection aso. will work;s = frozenset(1,2,3);python
If / elif / else;"if x > 10: pass
elif x > 10: pass
else: pass";python
Use 2 conditions in one line (instead of (a>10 and a<20);if (10 < a < 20)...;python
Connecting different control structures with logical and &;if a<10 & b>10 & c==4...;python
5 iterations from 0 to 4;for i in range(5):;python
5 iterations from 0 to 4 (start, end, step);for i in range(0, 5, 1);python
Iterations descending from 4 to 0;for i in range(4, -1, -1);python
While loop with break condition;while x < 4:;python
Endless while loop - has to be exited with break;while True:;python
Break loop completely;break;python
Break actual loop run - continue with next loop run;continue;python
description of the function in form of a docstring;"def printNumAbbr(value):
'''
eg. Make abbreviaton for numeric value in thousands (K), millions (M), billions (B) or trillions (T)
:param value: numeric value which should be abbreviated
:return: string value with maximum possible abbreviation
'''";python
Define function - with default value 0 if no input is given;"def add(x=0,y=0):
erg = x+y # Calculation in function
return erg # Return value from the function";python
Optional argument in the funtction (first element is must - second optional);"def pet (animal,n1=None,n2=""x"")
pet(""Cat"") # Calling function with n1=None and n2 = ""x""
pet(""Cat"",""name"") # Calling function with n1=name and n2 = ""X""
pet(""Cat"",n2=""xyz"") # Calling function with n1=None and n2 = ""xyz"" (third parameter has to be named when calling)";python
Function with infinite arguments;"def varargs(*args): print(args)
varargs(1,2,3) # Outputs (1,2,3)
def keyword_args(**kwargs):
print(kwargs)
keyword_args(""a""=3, ""b""=4) # Outputs {""a"":3, ""b"":4}";python
decorator template;"def my_decorator(func): # Define decorator
@functools.wraps(func)
def wrapper(*args,**kwargs): # Decorator with * arguments
#Do... # Do something before the functions
result=func(*args,**kwargs) # Run the function
#Do... # Do something after the functions
return result # Return the results from the function
return wrapper";python
decorator;"extend behaviour of a function with a decorators
def start_end_decorator(func): # Define the decorator with function ""func"" as input-parameter
def wrapper(): # Inside the decorator a wrapper function has to be defined
print(""Start"") # Decorated code which is executed before the core code from the function
func() # Calling the function itself
print(""End"") # Decorated code which is executed after the core code from the function
return wrapper # Results from the decorator have to be given back
@start_end_decorator # Defines this decorator for the following function ""print_name""
def print_name(): # Normal content of the function
print(""xyz"") # Core functionality of the function
print_name() # Now when the function is executed - outputs not only ""xyz"" - also ""Start"" before and ""End"" after";python
decorator with function arguments;"def start_end_decorator(func): # Define the decorator with function ""func"" as input-parameter
def wrapper(*args,**kwargs): # Inside the decorator a wrapper function has to be defined
print(""Start"") # Decorated code which is executed before the core code from the function
result = (*args,**kwargs) # Calling the function itself
print(""End "") # Decorated code which is executed after the core code from the function
return result
return wrapper # Results from the decorator have to be given back
@start_end_decorator # Defines this decorator for the following function ""add5""
def add5(x): # Normal content of the function with one argument
return x + 5 # Core functionality of the function
result = add5(10) # Outputs ""Start"" => ""End"" => 15
print(result)";python
Defines the generator with 3 yield statements;"def mygenerator():
yield 3
yield 2
yield 1";python
Creates the generator and stores in g (=generator type);g = mygenerator();python
Outputs 3,2,1;for i in g: print(i);python
Outputs 3;print(next(g));python
Outputs 2;print(next(g));python
Sum-Function can also use a generator => result is 6;sum(g);python
Sorted-Function can use generator => returns list with sorted elements [1,2,3];sorted(g);python
try / except;"try:
a = 5 / 0
except Exception as e:
print(""Exception: "",e) # Prints exception ""division by zero""";python
assert / raise;"x = -5
assert (x>=0), ""x is not positive"" # Checks / Assert some condition => prints ""x is not positive""
if x<0: raise Exception(""x should positive"") # Raises an exception => prints ""Exception: x should be positive""";python
functions with one argument - add10(5) => 15;add10 = lambda x: x+10;python
functions with two arguments for multiplying - mult(2,7) => 14;mult = lambda x,y: x*y;python
output is sorted with first element then second element => [(1,2),(5,-1),(10,4),(15,1)];sorted(p);python
output is sorted by the second element => [(5,-1),(15,1),(1,2),(10,4)];sorted(p,key=lambda x:x[1]);python
output is sorted by the sum of both => [(1,2),(5,-1),(10,4),(15,1)];sorted(p,key=lambda x:x[0]+x[1]);python
list is mapped with the lambda function => [2,4,6,8,10];list(map(lambda x: x*2,a));python
also possible with list comprehension => [2,4,6,8,10];c=[x*2 for x in a];python
list is filtered with lambda for even numbers => [2,4];list(filter(lambda x: x%2==0,a));python
also possible with list comprehension => [2,4];c=[x for x in a if x%2==0];python
Define a class;"class Human(object):
species = ""Homo Sapiens"" # Fix variable / class variable for all instances of the class
def __init__(self,name): # Constructor - automatically applied when an instance is created
self.name = name # Name is assigned to the instance of the classe (self.)
self.tresor = [] # Tresor is assigned as list to the instance of the class (self.)
def say(self, msg): # Methode of the class
return ""{name}: {message}"".format(name=self.name, message=msg)
elf.tresor.append(msg) # Tesor of the instance gets a new value in the list
@classmethod # Class methode - is used by all instances
def get_species(cls):
return cls.species
@staticmethod # Static methode - is called without class or method
def grunt():
return ""*grunt*""";python
Create instance of the class;"i = Human(name=""Ian"")";python
"Call the methode of the class (output: ""Ian: Hi"")";"print(i.say(""Hi""))";python
Create additonal instance of the class;"j = Human(name=""Joel"")";python
"Call the methode of the class (output: ""Joel: Hallo"")";"print(i.say(""Hallo""))";python
"Output ""Homo Sapiens""";i.get_species();python
"Same output ""Homo Sapiens""";j.get_species();python
Change of the class variable - applies for all instances;"Human.species = ""Was Neues""";python
"Aufruf der statischen Methode => Ausgabe: ""*grunt*""";Human.grunt();python
Dataclasses;"from dataclasses import dataclass # import dataclass necessary
@dataclass # define a dataclass
class Coordinate: # class is defined an need NO __init__, __repr__, __eq__
x: int # __init__ no necessary - values get assigned automatically
y: int = 10 # __repr__ print for the string-represantion is automatic => Coordinate(x=4, y=5)
a = Coordinate(4, 5)
@dataclass (frozen=True) # defines a unmutable instance
asdict(dc) # converts the dataclass to a dict
astuple(dc) # converts the dataclass to a tuple";python
Read textfile - and print it;"with open (""fn.txt"",""r"") as f: print(f.read()";python
Open File for Read and Write;"with open (""fn.txt"",""r+"") as f: print(f.read()";python
Read textfile - stored in list per line;"with open(fn, encoding=""utf8"", errors=""ignore"") as f:
lines = f.readlines()";python
Writing in textfile;"with open(""fn.txt"",""w"") as obj: obj.write(""Ein neuer Text"")";python
Append text in the next line;"with open(""fn.txt"",""a"") as obj: obj.write(""\nNoch ein Text"")";python
Check if file allready exists;if os.path.exists(fn) == False:;python
Create and initialize file when not exisiting;"with open (fn,""a"") as f: f.write(""init"")";python
Read content to string;f.read();python
Set the current postion in the file to beginning;f.seek(0);python
Write s to the f-file opened;f.write(s);python
Try/Except - checks if file can be saved;"while True:
try: # otherwise outputs a error message
writer.save ()
break
except Exception as e:
print(f""Error happened: {e}"")
traceback.print_exc() # Outputs the detailed error message
input (""File Open not possible - pls close and press <Enter>"")";python
Import json-module;import json;python
Assign JSON-filename;"fn = ""numbers.json""";python
Reading informations in json-format;with open(fn) as data: info = json.loads(data);python
Convert / Encode a dict to a json-file (with indent for better reading);json_format = json.dumps(d,indent=2);python
Convert / Encode a dict to a json-file (with sorting the keys);json_format = json.dumps(d,sort_keys=True);python
Convert / Decode a json-file to a dict;person = json.loads(json_format);python
Reading information in json-format;"with open(fn.json,""r"") as data: d=json.load(file)";python
Pretty-Print formatted json-file;print(json.dumps(erg, indent=4, sort_keys=True));python
when there are utf-8 errors pls try to set the system variables;"import sys
sys.stdin.reconfigure(encoding='utf-8')
sys.stdout.reconfigure(encoding='utf-8')";python
ignoring errors and handles multiple json-objects;"with open(fnJSON, errors=""ignore"") as f:
data = [json.loads(line) for line in f]";python
ignoring errors and handles multiple json-objects;"r = requests.get(tmpJSONWord)
jsonStrList = r.text.split(""\n"")
jsonList = [json.loads(j, errors=""ignore"") for j in jsonStrList if j != '']";python
write JSON to txt-file;"with open('dataDetail.json', 'w', encoding='utf-8') as f:
json.dump(ergDetail, f, ensure_ascii=False, indent=4)";python
Example for json-file;"{
""firstName"" : ""Chuck"",
""lastName"" : ""Doe"",
""hobbies"": [""running"",""swimming"",""singing""],
""age"": 28,
""hasChildren"": true
""children"" = [
{
""firstName"" : ""Alex""
""age"" : 5
},
{
""firstName"" : ""Bob""
""age"" : 7
}
]
}";python
"Read name value => ""Chuck""";"info[""firstName""]";python
Iterate trough the json-file (eg. many children);for item in children:;python
Import xml-module;import xml.etree.ElementTree as ET;python
Example for xml-file;"<persons>
<person>
<name>Chuck</name>
<phone type=""int1""> +1 734 555""</phone>
<email hide=""yes""/>
</person>
...
</persons>";python
Read xml-file into tree;tree = ET.fromstring(data);python
"Read name text => ""Chuck""";"tree.find(""name"").text";python
Read hide value from email => yes;"tree.find(""email"".get(""hide""))";python
Iterate trough xml-file (eg. many persons);"lst = persons.findall(""persons/person"")
for item in lst:";python
Import Module for URL parsing;import urllib.parse;python
Import Module for request;import urllib.request;python
Encode url;link = urllib.parse.quote_plus(link);python
Uncode url;link = urllib.parse.unquote_plus(link);python
Parse HTML-link1;"u = urlparse(""http://google.com/search"")";python
"Returns ""http""";u.scheme;python
"Returns ""/search""";u.path;python
"Returns ""google.com""";u.netloc;python
Download picture from a url;"opener = urllib.request.URLopener()
opener.addheader('User-Agent', ""Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36"")
filename, headers = opener.retrieve(url, 'Test.jpg')";python
Download xlsx/csv from a url;"from urllib.request import urlopen, urlretrieve
urlretrieve(hrefLink, filename)";python
Read csv-file to nested-list;"fn = os.path.join(path, ""inp.csv"")
with open(fn, ""r"", encoding=""utf-8"") as f:
csvRead = csv.reader(f, delimiter="";"")
inpData = [x for x in csvRead]
# when this error happens: _csv.Error: line contains NULL
with open(workFN, ""r"", encoding=""utf-16"") as f:
...
# when this error happens: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x96
with open(workFN, ""r"", encoding=""mac_roman"") as f:
...";python
Create an empty csv-file;"with open(fnName, ""w"") as f:
pass";python
Write csv-file from nested list;"FN = os.path.join(path, ""output.csv"")
with open(FN, 'w', newline='', encoding=""utf-8"") as f:
writer = csv.writer(f, delimiter="";"")
writer.writerows(l)";python
Read csv-file to a dictionary for every line;"with open (""products.csv"", ""r"", encoding=""utf-8"") as f:
dictReader = csv.DictReader(f)
for item in dictReader:
for k,v in item.items():
print(k,v)";python
Read csv-data from a HTML-link;"import urllib.request
import codecs
url = link # direct link to a csv html file
ftpstream = urllib.request.urlopen(url)
csvfile = csv.reader(codecs.iterdecode(ftpstream, 'utf-8')) # output is nested list";python
Import zip module;import zipfile;python
Read Zip-File;zf = zipfile.ZipFile('example.zip', 'r');python
List of string with the names of the files in the Zip-File;zf.namelist();python
Open file vom Zip-File (eg. CSV-File which is in the Zip-File);zf.open (file_name);python
https://techwithtim.net/tutorials/google-sheets-python-api-tutorial/;"# Create a project on https://console.cloud.google.com/
# select name + click create + select project
# 3 lines upper/left - API/Services - Library
# search for google drive API + enable it
# search for google sheets api + enable it
# 3 lines upper/left - API/Services - Credentials
# create credentials for Service Accounts + define name + press Continue
# choose role ""editor"" + press Continue + press Done
# press on created service account + press keys + Add Key + Create New Key
# select json + and store json-file with name creds.json
# copy client_email entry from the json-file
# in google sheets - got to share in the document
# paste the email from above + press send";python
https://jrizmal.medium.com/deploying-a-python-web-scraper-on-google-cloud-platform-12fe24e57bb0;"# select project (in titlebar right from Google Cloud Platform)
# create a function (search for cloud functions)
# set trigger (Cloud Pub/Sub) and create/select topic
# files needed for hosting: main.py (inside def hello_pubsub), requirements.txt, creds.json
# create schedule (search for cloud scheduler)";python
See further setup in tutorial;"import gspread # import module
import oauth2client # import module
from oauth2client.service_account import ServiceAccountCredentials # import module for account credentials
from pprint import pprint # import module for better output formatting
scope = [""https://spreadsheets.google.com/feeds"",
'https://www.googleapis.com/auth/spreadsheets',
""https://www.googleapis.com/auth/drive.file"",
""https://www.googleapis.com/auth/drive""]
creds = ServiceAccountCredentials.from_json_keyfile_name
(""creds.json"", scope)";python
Credentials Mgmt for GoogleSheets;gc = gspread.authorize(creds);python
Open the Google Sheet;"wb1 = gc.open(""NameOfSheet)";python
Open the first worksheet in the Google Sheet;ws1 = wb1.get_worksheet(0);python
Get all worksheets as worksheet-objects;listWS = wb1.worksheets();python
Get all worksheets by n;listWS = [x.title for x in wb1.worksheets()];python
Open the spreadhseet;"sheet = client.open(""testpython"").sheet1";python
Get a list of all records;dataList = ws1.get_all_values();python
Get specific area;data = ws1.get('B5:K8');python
Get formula of a cell;ws1.acell('B1', value_render_option='FORMULA').value;python
Update cell range with nested list;ws1.update('A1:Z10', [[1, 2], [3, 4]]);python
Insert new row at row number 2;"ws1.insert_row([""new1"",""new2"",""new3""],2)";python
Append new row at the end;"ws1.append_row([""new1"",""new2"",""new3""])";python
Sorting the sheet (Range + col1 asc + col2 desc);ws1.sort((1, 'asc'), (2, 'des'), range='A2:G20');python
Get row 3 (starts counting from 1 - not 0);row = sheet.row_values(3);python
Get col E (starts counting from 1 - not 0);col = sheet.col_values(5);python
Get values from col B rows 4 and 5;col = sheet.col_values(2)[3:5];python
Get the value from row 1 and col B;cell = sheet.cell(1,2).value;python
Update cell from row 2 and col B;"ws1.update_cell(2,2, ""CHANGED"")";python
Define cell area / cell row;cell_list = worksheet.range('A1:G1');python
Define new values for area / row;new_values = [1,2,3,4,5];python
https://pypi.org/project/gspread-formatting/;"# Set format for area:
from gspread_formatting import *
fmt = cellFormat(
backgroundColor=color(1, 0.9, 0.9),
textFormat=textFormat(bold=True, foregroundColor=color(1, 0, 1)),
horizontalAlignment='CENTER'
)
format_cell_range(worksheet, 'A1:J1', fmt)
# Conditional formatting
from gspread_formatting import *
worksheet = some_spreadsheet.worksheet('My Worksheet')
rule = ConditionalFormatRule(
ranges=[GridRange.from_a1_range('A1:A2000', worksheet)],
booleanRule=BooleanRule(
condition=BooleanCondition('NUMBER_GREATER', ['100']),
format=CellFormat(textFormat=textFormat(bold=True), backgroundColor=Color(1,0,0))
)
)
rules = get_conditional_format_rules(worksheet)
rules.append(rule)
rules.save()
# or, to replace any existing rules with just your single rule:
rules.clear()
rules.append(rule)
rules.save()";python
https://openpyxl.readthedocs.io/en/stable/api/openpyxl.worksheet.worksheet.html#openpyxl.worksheet.worksheet.Worksheet.PAPERSIZE_A3;Documentation:;python
Read xlsx;"wb = ox.load_workbook(""test.xlsx"")";python
Read worksheetnames to list;l = wb.sheetnames;python
Select specific worksheet in workbook;"ws = wb[""sheet1""]";python
Select first worksheet;ws = wb[wb.sheetnames[0]];python
Select active worksheet from workbook;ws = wb.active;python
Value from specific cell;"val = ws[""A1""].value";python
Import module for loading a workbook;from openpyxl import load_workbook;python
Import module for creating a workbook;from openpyxl import Workbook;python
Load xlsx;"wb = load_workbook((""Test.xlsx""))";python
Load xlsm;"wb = load_workbook(filename=""Test.xlsm"",";python
Create new workbook;wb = openpyxl.Workbook();python
Create new worksheet (at the end);"wb.create_sheet(""ws"")";python
Create new worksheet (at the beginning);"wb.create_sheet(""ws"",0)";python
Create new worksheet (at the second last position);"wb.create_sheet(""ws"",-2)";python
Change worksheet name;"ws.title = ""xyz""";python
Value from specific cell (other method);ws.cell(row=1, column=1).value;python
Assign value to specific cell;"ws[""A1""] = 97";python
"Assign formula to specific cell (only english names for function and arguments must be sepearted by "","" and not "";"")";"ws[""A1""] = ""=SUBTOTAL(1,I6:I10000)""";python
Save workbook to xlsx;"wb.save(""Test2.xlsx"")";python
Sort worksheets in workbook;wb._sheets.sort(key=lambda ws: ws.title);python
Copy worksheet in workbook;wb.copy_worksheet(ws);python
Copy part of the worksheet;ws1.range('A1:Z20').copy(wb2.sheets[0].range('A1:Z20'));python
Loop trough specific area and print the cell values;"for row in ws[""A1"":""C3""]:
for cell in row: print(cell.value)";python
Loop trough specific column and print the cell values;"for cell in ws[""C""]: print(cell.value)";python
Insert column before col 3;ws.insert_cols(3);python
Insert 2 columns before col 3;ws.insert_cols(3,2);python
Insert row before row 7;ws.insert_rows(7);python
Insert 5 rows before row 10;ws.insert_rows(10,5);python
Delete column C;ws.delete_cols(3);python
Delete column F to H;ws.delete_cols(6,3);python
Delete row 5;ws.delete_rows(5);python
Delete row 5 to 7;ws.delete_rows(5,3);python
Move the cells from D4:F10 up one row and right two columns;"ws.move_range(""D4:F10"", rows=-1, cols=2)";python
Append the values at the bottom of the sheet;"ws.append([1,""A"",2,""C""])";python
"Returns dimension of the worksheet eg. ""A1:M24""";ws.dimensions;python
Returns max column / row count of the worksheet;ws.max_column / ws.max_row;python
Returns min column / row count of the worksheet (which contains data);ws.min_column / ws.min_row;python
Rows 1:3 to be printed at the top of every page;ws.print_title_rows(1:3);python
Delete worksheet in workbook;"del wb[""sheet4""]";python
Define filters in columns A5 to Q5;"ws.auto_filter.ref = ""A5:Q5""";python
"Set filter to values ""X"",""Y"",""Z"" in column 2";"ws.auto_filter.add_filter_column(2,[""X"",""Y"",""Z""])";python
Sort elements in filter for columsn B2 to B15;"ws.auto_filter.add_sort_condition(""B2:B15"")";python
Close workbook;wb.close();python
Iterate trough worksheet row by row;"for row in ws.iter_rows():
for cell in row: print(cell.value)";python
Iterate trough worksheet row by row (from A1 to C6 - 6 lines);"for row in ws.iter_rows
(min_row=1,min_col=1,max_row=6,max_col=3):";python
Iterate trough worksheet col by col;"for col in sheet.iter_cols():
for cell in col: print(cell.value)";python
Iterate trough worksheet col by col (from A1 to C6 - 3 lines);"for col in ws.iter_cols
(min_row=1,min_col=1,max_row=6,max_col=3):";python
Read whole worksheet to a nested list;"data_list = []
for row in ws.iter_rows ():
zeile = []
for cell in row:
if cell.value is None:
zeile.append ('')
else:
zeile.append (cell.value)
data_list.append (zeile)";python
Saving a nested list in XLSX;"import pandas as pd
from openpyxl import load_workbook
cont = [[row1_cell1, row1_cell2], [row2.cell1,row3_cell3]] # Nested list for saving
book = load_workbook (""fn.xlsx"") # load existing XLSX - skip when overwriting
writer = pd.ExcelWriter (""fn.xlsx"", engine='openpyxl', # Define writer from pandas
options={'strings_to_numbers': True})
pd.DataFrame (cont).to_excel (writer, sheet_name=""WS1"", # Prepare Data for XLSX and worksheet1
header=False, index=False)
pd.DataFrame (cont).to_excel (writer, sheet_name=""WS2"", # Prepare Data for XLSX and worksheet2
header=False, index=False)
writer.save() # Save XLSX with the new worksheets
writer.close() # Close writer";python
Checking if xlsx is open while trying to save;"while True:
try:
writer.save ()
writer.close ()
break
except Exception as e:
print (""Error: "", e)
traceback.print_exc()
input (""Datei kann nicht geöffnet werden - bitte schließen und <Enter> drücken!"")";python
Read column to a list;"mylist = []
for col in ws['A']:
mylist.append(col.value)";python
Automatic adjustment of the columns accoring to best fit;"column_widths = []
ws = writer.sheets[stock]
for row in content: # Determination of the longest value per column
for i, cell in enumerate (row):
if len (column_widths) > i:
if len (str (cell)) > column_widths[i]:
column_widths[i] = len (str (cell))
else:
column_widths += [len (str (cell))]
for i, column_width in enumerate (column_widths): # Col 0 and 1 with fixed length - rest according to longest value in col
if i == 0:
ws.column_dimensions[get_column_letter (i + 1)].width = 35
elif i == 1:
ws.column_dimensions[get_column_letter (i + 1)].width = 32
else:
ws.column_dimensions[get_column_letter (i + 1)].width = column_width + 2";python
import openpyxl.styles;from openpyxl.styles import Font, PatternFill, Border, Side, Alignment;python
import formatting, styles;from openpyxl import formatting, styles;python
bold font;bold = Font (bold=True);python
yellow background (use color picker);"bg_yellow = PatternFill (fill_type=""solid"", start_color='fbfce1', end_color='fbfce1')";python
grey background (use color picker);"bg_grey = PatternFill (fill_type=""solid"", start_color='babab6', end_color='babab6')";python
blue background (use color picker);"bg_green = PatternFill (fill_type=""solid"", start_color='8af542', end_color='8af542')";python
define border on very side;"frame_all = Border (left=Side (style='thin'), right=Side (style='thin'),
top=Side (style='thin'), bottom=Side (style='thin'))";python
border only on top and bottom;frame_upanddown = Border (top=Side (style='thin'), bottom=Side (style='thin'));python
font size 14;"size14 = Font (bold=True, size=""14"")";python
define left alignment;"left_allign = Alignment (horizontal=""left"")";python
define right alignment;"right_allign = Alignment (horizontal=""right"")";python
define right alignment for area;"for row in ws[""D1"":""G34""]:
for cell in row: cell.alignment = right_allign";python
define full border for several areas;"areas = [""A7:G19"",""A27:G31""]";python
format area;"for area in areas:
for row in ws[area]:
for cell in row:
cell.border = frame_all
cell.number_format = ""0"" => define number format without decimals
cell.number_format = ""0.000E+00"" => define number format with 3 decimals";python
set background and size for several specific cells;"for i in [""A6"",""D6"",""E6"",""A26"",""D26"",""E26""]:
ws[i].fill = bg_green
ws[i].font = size12";python
freeze worksheet at cell B2 for right and down scrolling;"freeze = ws[""B2""]
ws.freeze_panes = freeze";python
fit xlsx to one page for printing - 1st part;ws.sheet_properties.pageSetUpPr.fitToPage = True;python
fit xlsx to one page for printing - 2nd part;ws.page_setup.fitToHeight = False;python
set page to landscape horizontal;ws.set_printer_settings(paper_size=1, orientation = 'landscape');python
set page to landscape horizontal;ws.set_printer_settings(paper_size=1, orientation = 'portrait');python
Define red color background;red_color = 'ffc7ce';python
Define red color font;red_color_font = '9c0103';python
Define red_font with size / bold / red color;red_font = styles.Font (size=14, bold=True, color=red_color_font);python
Define red_fill with color red / fill type solid;red_fill = styles.PatternFill (start_color=red_color, end_color=red_color, fill_type='solid');python
Define conditional formating for area, <0, fill with red background;"ws.conditional_formatting.add ('A1:Z100',
formatting.rule.CellIsRule (operator='lessThan',formula=['0'],fill=red_fill))";python
Define conditional formating for area, <0, use red font;"ws.conditional_formatting.add ('A1:G25',
formatting.rule.CellIsRule (operator='lessThan',formula=['0'],fill=red_fill,font=red_font))";python
Conditional formating for more than one area;"for area in [""B1:B100"",""C2:G100""]:
ws.conditional_formatting.add (area, ...)";python
Conditional formating according to a formula;"ws.conditional_formatting.add('E1:E10',
FormulaRule(formula=['ISBLANK(E1)'], stopIfTrue=True, fill=redFill))";python
Conditional formating according to a formula;"ws.conditional_formatting.add('D2:D10',
FormulaRule(formula=['E1=0'], font=myFont, border=myBorder, fill=redFill))";python
Color Scale formating;"# Define rule
ruleBottomGreen = ColorScaleRule(
start_type='percentile', start_value=10, start_color=""63BE7B"", # green
mid_type='percentile', mid_value=50, mid_color= ""FFFB84"", # yellow
end_type='percentile', end_value=90, end_color=""F8696B"") # red
# Apply rule
ws2.conditional_formatting.add(f""K4:K12"", ruleBottomGreen)";python
Import module;import xlwings as xw;python
Use xlwings with hidden excel-worksheets;app = xw.App(visible=False);python
Create a new workbook;wb = xw.Book();python
Read XLSX;"wb = xw.Book (""name.xlsx"")";python
Read XLSX with password protection;"wb = xw.Book (""name.xlsx"", password(""xyz""))";python
Read specific worksheet;"ws = wb.sheets[""name_sheet""]";python
Read first worksheet;ws = wb.sheets[0];python
Add worksheet in workbook;"wb.sheets.add(""NewWS"")";python
Reads the formula of a cell (not the value);"f = ws[""A1""].formula";python
Assign formula to a cell;"ws[""A1""].formula = string";python
"Iterate trough cells an set them to """" / None";"for i in ws.range(""A3:A7""): i.value = """"";python
Sort worksheet in the first col (function see below);xl_col_sort(ws,1);python
Reads the color of a cell and returns a rgb-tuple eg. (146, 208, 80);"ws[""C8""].color";python
Set value for cell;"ws[""C8""].value";python
Read hyperlink of cell;"ws.range (""A2"").hyperlink";python
Set values for specific cell;"ws.range(""A1:C3"").value";python
Remove background from a cell;"ws[""C8""].color = None";python
White: Assigns background color for a range of cells;"ws.range(""A1:C3"").color = (255,255,255)";python
Green: Assigns background color;"ws.range(""A1:C3"").color = (149,237,173)";python
Red: Assigns background color;"ws.range(""A1:C3"").color = (237,149,149)";python
Yellow: Assigns background color;"ws.range(""A1:C3"").color = (240,232,146)";python
Orange: Assigns background color;"ws.range(""A1:C3"").color = (230,172,80)";python
Blue: Assigns background color;"ws.range(""A1:C3"").color = (143,157,235)";python
Assign numeric format with 2 decimals;"ws.range(""A1:C3"").number_format = ""0,00""";python
Assign percentage format with 2 decimals;"ws.range(""A1:C3"").number_format = ""0%""";python
Set cell to bold;"ws.range(""B1"").api.Font.Bold = True";python
Windows: Black: Set font color to black (see codes: https://access-excel.tips/excel-vba-color-code-list/);"ws.range(""B2"").api.Font.ColorIndex = 1";python
Windows: Red: Set font color to red (see codes: https://access-excel.tips/excel-vba-color-code-list/);"ws.range(""B2"").api.Font.ColorIndex = 3";python
Windows: Set font size to 16;"ws.range(""A1"").api.Font.Size = 16";python
Windwos: Set specific font;"ws.range(""A1"").api.Font.Name = ""Arial""";python
Mac: Set font color to dark grey;"ws.range(""B2"").api.font_object.color.set((105,105,105))";python
Autofit the columns;"ws2.autofit(axis=""columns"")";python
Autofit the columns and rows;ws2.autofit();python
Set wrap text to False;"ws2.range(f""A2:Z10000"").api.WrapText = False";python
Insert a hyperlink and define which text should be shown in the cell;"ws[""D5""].add_hyperlink(link, text_to_display = ""Chart"")";python
add an image at a specific cell;"wsInp.pictures.add(imgFN, left=wsInp.range(""D20"").left, top=wsInp.range(""D20"").top, height=100)";python
Get all the pictures of a worksheet in a list;ws.pictures;python
Delete the first picture in the worksheet;ws.pictures[0].delete();python
"Delete the first picture with the name ""xyz""";"ws.pictures[""xyz""].delete()";python
Disable auto filter in worksheet;ws.api.AutoFilterMode = False;python
Clears the content and formatting of the whole sheet;ws.clear();python
Clears the content but leaves formatting;ws.clear_contents();python
Read worksheetnames to list;l = [x.name for x in wb.sheets];python
Delete worksheet in workbook;"wb.sheets[""OldWS""].delete()";python
Hide worksheet in workbook;"wb.sheets[""WS""].api.Visible = False";python
Copy worksheet;ws.copy(name='copied');python
Save workbook;wb.save();python
Close workbook;wb.close();python
Quit App when opened at the beginning;wb.quit();python
Bring workbook to the front of the screen;wb.activate(steal_focus=True);python
Load elements in list from range which are not None;"[x for x in ws.range(""A3:A2000"").value if x != None]";python
copy range from one sheet to another;"ws.range(""A1:A10"").value = ws2.range(""A1:A10"").options(ndim=2).value";python
Move worksheet at the beginning;ws1.api.Move(Before=wsWork.api);python
Move worksheet at the end;ws1.api.Move(After=wsWork.api);python
Get address and subaddress from hyperlinks;"for l in ws1['H18'].api._inner.Hyperlinks:
wAddr = l.address # brings results for http-links
wSubAddr = l.SubAddress # brings results for internal file-links";python
Hide worksheet in windows;"app = xw.App()
wb = app.books.open(FN)
app.visible = False
ws = wb.sheets[0]";python
Definiton for border-sites see: https://docs.microsoft.com/en-us/office/vba/api/excel.xlbordersindex;"for e in ws.range(""B3:D3""):
for site in [7,8,9,10]:
e.api.Borders(site).LineStyle = 1";python
Update row / change whole row;"l = ws.range(""A2:A6"").value # Read specific cells to list (eg. [2,4,6,7,8])
l = [0,1,2,3,4] # Change list
ws.range(""A2:A100"").value = l # Writeback the updates to cells";python
Update cell area / change 3 elements;"v = ws.range(""A2:F9"").value
v[3][2] = 9999999
v[5][1] = 8888888
v[7][5] = 5555555
ws.range(""A2:F9"").value = v";python
Sorting workssheet in given col;"def xl_col_sort(sheet,col_num):
sheet.range((2,col_num)).api.Sort(Key1=sheet.range((2,col_num)).api, Order1=1)
return";python
Delete several rows / columns;"from xlwings.constants import DeleteShiftDirection
ws.range('2:4').api.Delete(DeleteShiftDirection.xlShiftUp) # delete rows 2 to 4
ws.range('A:C').api.Delete(DeleteShiftDirection.xlShiftUp) # delete cols A to C";python
Import the module;import python-docx;python
Import the library;from docx import Document;python
Read file;doc = Document('file.docx');python
Save file;doc.save('file.docx');python
Read all tables;t = doc.tables;python
Access specific element in table;t[0].rows[0].cells[0].paragraphs[0].text;python
Assign style to specific paragraph;t[0].rows[0].cells[1].paragraphs[0].style;python
Read all paragraphs;p = doc.paragrapsh;python
Set the Normal style to specific font and size;"(assigning it to specific paragraph see above)
from docx.shared import Pt
style = document.styles['Normal']
font = style.font
font.name = 'Arial'
font.size = Pt(10)";python
Replace text and keep the previous style;"(iteration over runs necessary)
for para in doc.paragraphs:
for run in para.runs:
run.text = ""New Text""";python
Import Win32 Module;import win32com.client;python
Import OS Module;import os;python
Define Input-XLSX;"inp = os.getcwd() + ""\\"" +""excel.xlsx""";python
Define Output-PDF;"out = os.getcwd() + ""\\"" +""ws.pdf""";python
Initialize Excel Application;"o = win32com.client.Dispatch(""Excel.Application"")";python
Do everything hidden;o.Visible = False;python
Open XLSX;wb = o.Workbooks.Open(inp);python
Create PDF from the active worksheet in the xlsx;wb.ActiveSheet.ExportAsFixedFormat (0, out);python
Close XLSX;wb.Close(True);python
Number of Worksheets;wb.Sheets.Count;python
Select 3 different worksheets by number (for exporting afterwards);wb.WorkSheets ([3,4,8]).Select();python
Assign worksheet 4;ws = wb.Worksheets[4];python
No Zooming;ws.PageSetup.Zoom = False;python
Fit to 1 height;ws.PageSetup.FitToPagesTall = 1;python