-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNectarStringPathOsFile
More file actions
1483 lines (978 loc) · 41.8 KB
/
NectarStringPathOsFile
File metadata and controls
1483 lines (978 loc) · 41.8 KB
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
http://stackoverflow.com/questions/tagged/python?sort=votes&pageSize=15
****************
How can I call an external command (as if I'd typed it at the Unix shell or Windows command prompt)
from within a Python script?
from subprocess import call
call(["ls", "-l"])
The advantage of subprocess vs system is that it is more flexible
(you can get the stdout, stderr, the "real" status code, better error handling, etc...).
I think os.system is deprecated, too, or will be:
Here's a summary of the ways to call external programs and the advantages and disadvantages of each:
os.system("some_command with args") passes the command and arguments to your system's shell. This is nice because you can actually run multiple commands at once in this manner and set up pipes and input/output redirection. For example,
os.system("some_command < input_file | another_command > output_file")
However, while this is convenient, you have to manually handle the escaping of shell characters such as spaces, etc. On the other hand, this also lets you run commands which are simply shell commands and not actually external programs.
see documentation
stream = os.popen("some_command with args") will do the same thing as os.system except that it gives you a file-like object that you can use to access standard input/output for that process. There are 3 other variants of popen that all handle the i/o slightly differently. If you pass everything as a string, then your command is passed to the shell; if you pass them as a list then you don't need to worry about escaping anything.
see documentation
The Popen class of the subprocess module. This is intended as a replacement for os.popen but has the downside of being slightly more complicated by virtue of being so comprehensive. For example, you'd say
print subprocess.Popen("echo Hello World", shell=True, stdout=subprocess.PIPE).stdout.read()
instead of
print os.popen("echo Hello World").read()
but it is nice to have all of the options there in one unified class instead of 4 different popen functions.
see documentation
The call function from the subprocess module. This is basically just like the Popen class and takes all of the same arguments, but it simply waits until the command completes and gives you the return code. For example:
return_code = subprocess.call("echo Hello World", shell=True)
see documentation
The os module also has all of the fork/exec/spawn functions that you'd have in a C program, but I don't recommend using them directly.
The subprocess module should probably be what you use.
Finally please be aware that for all methods where you pass the final command to be executed by the shell as a string and you are responsible for escaping it there are serious security implications if any part of the string that you pass can not be fully trusted (for example if a user is entering some/any part of the string). If unsure only use these methods with constants. To give you a hint of the implications consider this code
print subprocess.Popen("echo %s " % user_input, stdout=PIPE).stdout.read()
and imagine that the user enters "my mama didnt love me && rm -rf /".
subprocess.call(['ping', 'localhost'])
import os
cmd = 'ls -al'
os.system(cmd)
------------------------------------------------------------------------------------------------------
How do I check whether a file exists, using Python, without using a try statement?
import os.path
os.path.isfile(fname)
import os.path
os.path.exists(file_path)
This returns True for both files and directories.
Use os.path.isfile to test if it's a file specifically.
try:
f = open(filepath)
except IOError:
print 'Oh dear.'
------------------------------------------------------------------------------------------------------
How do I copy a file in Python ?
shutil has many methods you can use. One of which is:
copyfile(src, dst)
Copy the contents of the file named src to a file named dst. The destination location must be writable; otherwise,
an IOError exception will be raised. If dst already exists, it will be replaced. Special files such as character
or block devices and pipes cannot be copied with this function. src and dst are path names given as strings.
import shutil
shutil.copy2('/dir/file.ext', '/new/dir/newname.ext')
or
shutil.copy2('/dir/file.ext', '/new/dir')
copy2 is also often useful, it preserves the original modification and access info (mtime and atime) in the file metadata.
------------------------------------------------------------------------------------------------------
Python: read file line by line into array ?
with open('filename') as f:
lines = f.readlines()
or with stripping the newline character:
lines = [line.rstrip('\n') for line in open('filename')]
Editor's note: This answer's original whitespace-stripping command, line.strip(), as implied
by Janus Troelsen's comment, would remove all leading and trailing whitespace, not just the trailing \n.
with open("file.txt", "r") as ins:
array = []
for line in ins:
array.append(line)
This will yield an "array" of lines from the file.
lines = tuple(open(filename, 'r'))
If you want the \n included:
with open(fname) as f:
content = f.readlines()
If you do not want \n included:
with open(fname) as f:
content = f.read().splitlines()
This should encapsulate the open command.
array = []
with open("file.txt", "r") as f:
for line in f:
array.append(line)
Here's one more option by using list comprehensions on files;
lines = [line.rstrip() for line in open('file.txt')]
------------------------------------------------------------------------------------------------------
Calling a function of a module from a string with the function's name in Python ?
Assuming module foo with method bar:
import foo
methodToCall = getattr(foo, 'bar')
result = methodToCall()
As far as that goes, lines 2 and 3 can be compressed to:
result = getattr(foo, 'bar')()
if that makes more sense for your use case. You can use getattr in this fashion on class instance bound methods,
module-level methods, class methods... the list goes on.
hasattr or getattr can be used to determine if a function is defined.
I had a database mapping (eventType and handling functionName) and I wanted to make sure I never "forgot" to define an event handler in my python
locals()["myfunction"]()
or
globals()["myfunction"]()
locals returns a dictionary with a current local symbol table. globals returns a dictionary with global symbol table.
import foo
m = foo
func = getattr(m,'bar')
func()
------------------------------------------------------------------------------------------------------
Reverse a string in Python ?
>>> 'hello world'[::-1]
'dlrow olleh'
------------------------------------------------------------------------------------------------------
GENERATION ALEATOIRE DE PLAQUES
>>> import string
>>> import random
>>> def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
... return ''.join(random.choice(chars) for _ in range(size))
...
>>> id_generator()
'G5G74W'
>>> id_generator(3, "6793YUIO")
'Y3U'
How does it work ?
We import string, a module that contains sequences of common ASCII characters, and random, a module that deals with random generation.
string.ascii_uppercase + string.digits just concatenates the list of characters representing uppercase ASCII chars and digits:
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits
'0123456789'
>>> string.ascii_uppercase + string.digits
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
ou tout simplement :
''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))
------------------------------------------------------------------------------------------------------
How to convert string to lowercase in Python ?
s = "Kilometer"
print(s.lower())
This doesn't work for non-english words in utf-8. In this case decode('utf-8') can help.
>>> s='????????'
>>> print s.lower()
_en russe_
>>> print s.decode('utf-8').lower()
_en russe_
http://stackoverflow.com/questions/6797984/how-to-convert-string-to-lowercase-in-python
------------------------------------------------------------------------------------------------------
http://stackoverflow.com/questions/tagged/python?page=6&sort=votes&pagesize=15
How to print in Python without newline or space?
print('.', end="")
Or if you are having trouble with the buffer , you can do this:
print('.',end="",flush=True)
>>> print "." * 10
..........
>>> for i in range(10):
... print i,
... else:
... print
...
0 1 2 3 4 5 6 7 8 9
>>>
------------------------------------------------------------------------------------------------------
How do you append to a file in Python ?
with open("test.txt", "a") as myfile:
myfile.write("appended text")
------------------------------------------------------------------------------------------------------
How to trim whitespace (including tabs)?
Whitespace on the both sides:
s = " \t a string example\t "
s = s.strip()
Whitespace on the right side:
s = s.rstrip()
Whitespace on the left side:
s = s.lstrip()
As thedz points out, you can provide an argument to strip arbitrary characters to any of these
functions like this:
s = s.strip(' \t\n\r')
This will strip any space, \t, \n, or \r characters from the left-hand side, right-hand side,
or both sides of the string.
Python trim method is called strip:
str.strip() #trim
str.lstrip() #ltrim
str.rstrip() #rtrim
------------------------------------------------------------------------------------------------------
How can I find all files in directory with the extension .txt in python ?
You can use glob:
import glob, os
os.chdir("/mydir")
for file in glob.glob("*.txt"):
print(file)
or simply os.listdir:
import os
for file in os.listdir("/mydir"):
if file.endswith(".txt"):
print(file)
or if you want to traverse directory, use os.walk:
import os
for root, dirs, files in os.walk("/mydir"):
for file in files:
if file.endswith(".txt"):
print(os.path.join(root, file))
>>> import os
>>> path = '/usr/share/cups/charmaps'
>>> text_files = [f for f in os.listdir(path) if f.endswith('.txt')]
>>> text_files
['euc-cn.txt', 'euc-jp.txt', 'euc-kr.txt', 'euc-tw.txt', ... 'windows-950.txt']
------------------------------------------------------------------------------------------------------
Nicest way to pad zeroes to string
>>> n = '4'
>>> print n.zfill(3)
>>> '004'
------------------------------------------------------------------------------------------------------
How to flush output of Python print?
import sys
sys.stdout.flush()
//
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
------------------------------------------------------------------------------------------------------
http://stackoverflow.com/questions/tagged/python?page=6&sort=votes&pagesize=15
Find current directory and file's directory ?
os.path.dirname(os.path.realpath(__file__))
To find the path of the current file you can use the os module (os.path in particular) and os.path.realpath(__file__).
To get the path of another file replace __file__ with the path of the file you wish to execute to determine its location.
Current Working Directory: os.getcwd()
And the __file__ attribute can help you find out where the file you are executing is located
//
You may find this useful as a reference:
import os
print("Path at terminal when executing this file")
print(os.getcwd() + "\n")
print("This file path, relative to os.getcwd()")
print(__file__ + "\n")
print("This file full path (following symlinks)")
full_path = os.path.realpath(__file__)
print(full_path + "\n")
print("This file directory and name")
path, file = os.path.split(full_path)
print(path + ' --> ' + file + "\n")
print("This file directory only")
print(os.path.dirname(full_path))
//
To get the current directory folder name alone
>>import os
>>str1=os.getcwd()
>>str2=str1.split('\\')
>>n=len(str2)
>>print str2[n-1]
dirname, filename = os.path.split(os.path.abspath(__file__))
------------------------------------------------------------------------------------------------------
Extracting extension from filename in Python ?
Use os.path.splitext:
>>> import os
>>> filename, file_extension = os.path.splitext('/path/to/somefile.ext')
>>> filename
'/path/to/somefile'
>>> file_extension
'.ext'
One option may be splitting from dot:
>>> filename = "example.jpeg"
>>> filename.split(".")[-1]
'jpeg'
No error when file doesn't have an extension:
>>> "filename".split(".")[-1]
'filename'
But you must be careful:
>>> "png".split(".")[-1]
'png' # But file doesn't have an extension
//
filename='ext.tar.gz'
extension = filename[filename.rfind('.'):]
------------------------------------------------------------------------------------------------------
ASCII value of a character in Python ?
>>> ord('a')
97
>>> chr(97)
'a'
>>> chr(ord('a') + 3)
'd'
>>>
There is also the unichr function, returning the Unicode character whose ordinal is the unichr argument:
>>> unichr(97)
u'a'
>>> unichr(1234)
u'\u04d2'
------------------------------------------------------------------------------------------------------
How can I get a list of locally installed Python modules ?
help('modules')
//
I just use this to see currently used modules:
import sys as s
s.modules.keys()
which shows all modules running on your python.
For all built-in modules use:
s.modules
Which is a dict containing all modules and import objects.
------------------------------------------------------------------------------------------------------
How to get file creation & modification date/times in Python ?
You have a couple of choices. For one, you can use the os.path.getmtime and os.path.getctime functions:
import os.path, time
print "last modified: %s" % time.ctime(os.path.getmtime(file))
print "created: %s" % time.ctime(os.path.getctime(file))
Your other option is to use os.stat:
import os, time
(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(file)
print "last modified: %s" % time.ctime(mtime)
------------------------------------------------------------------------------------------------------
How do I get a list of all files (and directories) in a given directory in Python ?
This is a way to traverse every file and directory in a directory tree:
import os
for dirname, dirnames, filenames in os.walk('.'):
# print path to all subdirectories first.
for subdirname in dirnames:
print(os.path.join(dirname, subdirname))
# print path to all filenames.
for filename in filenames:
print(os.path.join(dirname, filename))
# Advanced usage:
# editing the 'dirnames' list will stop os.walk() from recursing into there.
if '.git' in dirnames:
# don't go into any .git directories.
dirnames.remove('.git')
//
os.listdir(path)
//
Here's a helper function I use quite often:
import os
def listdir_fullpath(d):
return [os.path.join(d, f) for f in os.listdir(d)]
------------------------------------------------------------------------------------------------------
How to access environment variables from Python?
Environment variables are accessed through os.environ
import os
print os.environ['HOME']
# using get will return `None` if a key is not present rather than raise a `KeyError`
print os.environ.get('KEY_THAT_MIGHT_EXIST')
# os.getenv is equivalent, and can also give a default value instead of `None`
print os.getenv('KEY_THAT_MIGHT_EXIST', default_value)
Python default installation on Windows is C:\Python. If you want to find out while running python you can do:
import sys
print sys.prefix
------------------------------------------------------------------------------------------------------
Limiting floats to two decimal points ?
>>> a
13.949999999999999
>>> print("%.2f" % round(a,2))
13.95
>>> print("{0:.2f}".format(a))
13.95
>>> print("{0:.2f}".format(round(a,2)))
13.95
>>> print("{0:.15f}".format(round(a,2)))
13.949999999999999
------------------------------------------------------------------------------------------------------
How to get line count cheaply in Python ?
def file_len(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
is it possible to do any better?
//
One line, probably pretty fast:
num_lines = sum(1 for line in open('myfile.txt'))
------------------------------------------------------------------------------------------------------
http://stackoverflow.com/questions/tagged/python?page=9&sort=votes&pagesize=15
how-do-i-protect-python-code
Terminating a Python script ?
import sys
sys.exit("some error message")
Another way is:
raise SystemExit
#do stuff
if this == that:
quit()
------------------------------------------------------------------------------------------------------
mkdir -p functionality in python ?
In Python >=3.2, that's
os.makedirs(path, exist_ok=True)
------------------------------------------------------------------------------------------------------
How do I remove/delete a folder that is not empty with Python ?
I am getting an 'access is denied' error when I attempt to delete a folder that is not empty. I used the following command in my attempt: os.remove("/folder_name").
What is the most effective way of removing/deleting a folder/directory that is not empty?
import shutil
shutil.rmtree('/folder_name')
------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------
Convert hex string to int in Python ?
I may have it as "0xffff" or just "ffff"
Without the 0x prefix, you need to specify the base explicitly, otherwise there's no way to tell:
x = int("deadbeef", 16)
With the 0x prefix, Python can distinguish hex and decimal automatically:
>>> print int("0xdeadbeef", 0)
3735928559
>>> print int("10", 0)
10
//
int(hexString, 16) does the trick, and works with and without the 0x prefix:
>>> int("a", 16)
10
>>> int("0xa",16)
10
//
For any given string s:
int(s, 16)
------------------------------------------------------------------------------------------------------
Convert bytes to a Python string ?
You need to decode the bytes object to produce a string:
>>> b"abcde"
b'abcde'
# utf-8 is used here because it is a very common encoding, but you
# need to use the encoding your data is actually in.
>>> b"abcde".decode("utf-8")
'abcde'
------------------------------------------------------------------------------------------------------
How can I tell if a string repeats itself in Python ?
Here's a concise solution which avoids regular expressions and slow in-Python loops:
def principal_period(s):
i = (s+s).find(s, 1, -1)
return None if i == -1 else s[:i]
//
Here's a solution using regular expressions.
import re
REPEATER = re.compile(r"(.+?)\1+$")
def repeated(s):
match = REPEATER.match(s)
return match.group(1) if match else None
------------------------------------------------------------------------------------------------------
How to find if directory exists in Python ?
You're looking for os.path.isdir, or os.path.exists if you don't care whether it's a file or a directory.
Example:
import os
print(os.path.isdir("/home/el"))
print(os.path.exists("/home/el/myfile.txt"))
------------------------------------------------------------------------------------------------------
Is there a portable way to get the current username in Python ?
>>> import getpass
>>> getpass.getuser()
'kostya'
//
import os
import pwd
def get_username():
return pwd.getpwuid( os.getuid() )[ 0 ]
//
os.getlogin()
//
os.getenv('USERNAME')
//
>>> os.path.expanduser('~')
'C:\\Documents and Settings\\johnsmith'
------------------------------------------------------------------------------------------------------
Parsing values from a JSON file in Python ?
import json
from pprint import pprint
with open('data.json') as data_file:
data = json.load(data_file)
pprint(data)
------------------------------------------------------------------------------------------------------
how to check file size in python ?
Use os.stat, and use the st_size member of the resulting object:
>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
(33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
>>> statinfo.st_size
926L
//
>>> import os
>>> b = os.path.getsize("/path/isa_005.mp3")
>>> b
2071611L
//
# f is a file-like object.
f.seek(0, os.SEEK_END)
size = f.tell()
------------------------------------------------------------------------------------------------------
How do I “cd” in python ?
os.chdir(path)
//
import subprocess # just to call an arbitrary command e.g. 'ls'
# enter the directory like this:
with cd("~/Library"):
# we are in ~/Library
subprocess.call("ls")
# outside the context manager we are back wherever we started.
//
os.chdir("/path/to/change/to")
By the way, if you need to figure out your current path, use os.getcwd()
------------------------------------------------------------------------------------------------------
Python - Split Strings with Multiple Delimiters ?
"Hey, you - what are you doing here!?"
should be
['hey', 'you', 'what', 'are', 'you', 'doing', 'here']
==>
import re
DATA = "Hey, you - what are you doing here!?"
print re.findall(r"[\w']+", DATA)
//
>>> 'a;bcd,ef g'.replace(';',' ').replace(',',' ').split()
['a', 'bcd', 'ef', 'g']
//
>>> import re
>>> # Splitting on: , <space> - ! ? :
>>> filter(None, re.split("[, \-!?:]+", "Hey, you - what are you doing here!?"))
['Hey', 'you', 'what', 'are', 'you', 'doing', 'here']
//
import string
punc = string.punctuation
thestring = "Hey, you - what are you doing here!?"
s = list(thestring)
''.join([o for o in s if not o in punc]).split()
------------------------------------------------------------------------------------------------------
Use a Glob() to find files recursively in Python ?
Use os.walk to recursively walk a directory and fnmatch.filter to match against a simple expression:
import fnmatch
import os
matches = []
for root, dirnames, filenames in os.walk('src'):
for filename in fnmatch.filter(filenames, '*.c'):
matches.append(os.path.join(root, filename))
//
import os, fnmatch
def find_files(directory, pattern):
for root, dirs, files in os.walk(directory):
for basename in files:
if fnmatch.fnmatch(basename, pattern):
filename = os.path.join(root, basename)
yield filename
for filename in find_files('src', '*.c'):
print 'Found C source:', filename
-------------------------------------------------------------------------------------------------------
Remove empty strings from a list of strings ?
My idea looks like this:
while '' in str_list:
str_list.remove('')
===>
I would use filter:
str_list = filter(None, str_list) # fastest
str_list = filter(bool, str_list) # fastest
str_list = filter(len, str_list) # a bit of slower
str_list = filter(lambda item: item, str_list) # slower than list comprehension
//
strings = ["first", "", "second"]
[x for x in strings if x]
Output: ['first', 'second']
-------------------------------------------------------------------------------------------------------
In Python, how do I get a function name as a string without calling the function?
def my_function():
pass
print get_function_name_as_string(my_function) # my_function is not in quotes
should output "my_function".
==>
my_function.__name__
Using __name__ is the preferred method as it applies uniformly. Unlike func_name, it works on built-in functions as well:
>>> import time
>>> time.time.func_name
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'builtin_function_or_method' object has no attribute 'func_name'
>>> time.time.__name__
'time'
Also the double underscores indicate to the reader this is a special attribute.
As a bonus, classes and modules have a __name__ attribute too, so you only have remember one special name.
//
import sys
this_function_name = sys._getframe().f_code.co_name
//
my_function.func_name
There are also other fun properties of functions. Type dir(func_name) to list them. func_name.func_code.co_code is the compiled function, stored as a string.
import dis
dis.dis(my_function)
will display the code in almost human readable format. :)
-------------------------------------------------------------------------------------------------------
Display number with leading zeros ?
a = 1
b = 10
c = 100
I want to display a leading zero for all numbers with less than 2 digits, i.e.:
01
10
100
==>
Here you are:
print "%02d" % (1,)
//
You can use zfill:
print str(1).zfill(2)
print str(10).zfill(2)
print str(100).zfill(2)
-------------------------------------------------------------------------------------------------------
How do I read a text file into a string variable in Python ?
I use the following code segment to read a file in python
with open ("data.txt", "r") as myfile:
data=myfile.readlines()
input file is
LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN
GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE
and when I print data I get
['LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN\n', 'GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE']
As I see data is in list form. How do I make it string. And also how do I remove "\n", "[", and "]" characters from it ?
===>
with open ("data.txt", "r") as myfile:
data=myfile.read().replace('\n', '')
//
use read(), not readline()
data=myfile.read()
//
with open("data.txt") as myfile:
data="".join(line.rstrip() for line in myfile)
-------------------------------------------------------------------------------------------------------
How to get an absolute file path in Python ?
>>> import os
>>> os.path.abspath("mydir/myfile.txt")
//
You could use the new Python 3.4 library pathlib. (You can also get it for Python 2.6 or 2.7 using pip install pathlib.) The authors wrote: "The aim of this library is to provide a simple hierarchy of classes to handle filesystem paths and the common operations users do over them."
To get an absolute path in Windows:
>>> from pathlib import Path
>>> p = Path("pythonw.exe").resolve()
>>> p
WindowsPath('C:/Python27/pythonw.exe')
>>> str(p)
'C:\\Python27\\pythonw.exe'
Or on UNIX:
>>> from pathlib import Path
>>> p = Path("python3.4").resolve()
>>> p
PosixPath('/opt/python3/bin/python3.4')
>>> str(p)
'/opt/python3/bin/python3.4'
-------------------------------------------------------------------------------------------------------
How can I use Python to get the system hostname ?
Both of these are pretty portable:
import platform
platform.node()
import socket
socket.gethostname()
import os
myhost = os.uname()[1]
-------------------------------------------------------------------------------------------------------
Best way to strip punctuation from a string in Python ?
exclude = set(string.punctuation)
s = ''.join(ch for ch in s if ch not in exclude)
This is faster than s.replace with each char, but won't perform as well as non-pure python approaches such as regexes or string.translate, as you can see from the below timings. For this type of problem, doing it at as low a level as possible pays off.
Timing code:
import re, string, timeit
s = "string. With. Punctuation"
exclude = set(string.punctuation)
table = string.maketrans("","")
regex = re.compile('[%s]' % re.escape(string.punctuation))
def test_set(s):
return ''.join(ch for ch in s if ch not in exclude)
def test_re(s): # From Vinko's solution, with fix.
return regex.sub('', s)
def test_trans(s):