Python Tips (my memo)

important point

Handle files under the directory

To read all files under "/ path / to".

import glob

for file in glob.glob('/path/to/*'):

  f = open(file, 'r')
  
  for line in f.readlines():
    print line
    
  f.close()

Get datetime for this Monday and Sunday

import datetime

today = datetime.datetime.today()

this_monday = today - datetime.timedelta(today.weekday())
this_sunday = today + datetime.timedelta(6 - today.weekday())

print 'Today: ' + today.ctime()
print 'Monay: ' + this_monday.ctime()
print 'Sunday: ' + this_sunday.ctime()

Result

Today: Fri Jun 19 13:20:59 2015
Monay: Mon Jun 15 13:20:59 2015
Sunday: Sun Jun 21 13:20:59 2015

Fill with 0 when returning a numeric type to a character string type

For example, convert a 1-digit number to a 4-digit character string and fill the left with 0.

num = 1

('0' * 4 + str(num))[-4:]

Result

'0001'

Create a dictionary / dictionary from two lists

>>> a = ['a', 'b', 'c']
>>> b = [1,2,3]
>>> dict(zip(a,b))
{'a': 1, 'c': 3, 'b': 2}

Sort by key when converting dictionary type to json in json library

in json.dump

sort_keys=True

Just pass.

>>> import json
>>>
>>> d = {'b':1, 'a':2, 'c':3}
>>>
>>> json.dumps(d)
'{"a": 2, "c": 3, "b": 1}'
>>>
>>> json.dumps(d, sort_keys=True)
'{"a": 2, "b": 1, "c": 3}'
>>>

Convert comma-separated numeric strings to numbers

Remove the comma with replace.

>>> '5,007,167,488'.replace(',','')
'5007167488'
>>> int('5,007,167,488'.replace(',',''))
5007167488

Recommended Posts

Python Tips (my memo)
[My memo] python
My python environment memo
[My memo] python -v / python -V
python tips
Python memo
python memo
Python memo
python memo
Python memo
Python memo
Python Tips
Python tips
Python memo
Python Conda Tips
My Numpy (Python)
My sys (python)
[Python] Memo dictionary
My pyproj (python)
My pandas (python)
My str (python)
python beginner memo (9.2-10)
My pyautogui (python)
python beginner memo (9.1)
Python click tips
Unexpectedly (?) Python tips
[Python] EDA memo
Python 3 operator memo
My PySide (Python)
My shutil (python)
My matplotlib (python)
My urllib (python)
My pyperclip (python)
My sklearn (python)
Python3 metaclass memo
[Python] Basemap memo
My ConfigParser (Python)
My Webdriver (Python)
My arcpy (python)
Python beginner memo (2)
[Python] Numpy memo
My win32gui (Python)
My os (python)
Python class (Python learning memo ⑦)
Python and numpy tips
python openCV installation (memo)
Python module (Python learning memo ④)
[Tips] My Pandas Note
[My memo] Preparing Django-Starting
My Beautiful Soup (Python)
Python test package memo
[Python] Memo about functions
python regular expression memo
Binary search (python2.7) memo
Python3 List / dictionary memo
[Memo] Python3 list sort
[Python] Memo about errors
DynamoDB Script Memo (Python)
Python basic memo --Part 2
python recipe book Memo
Basic Python command memo