Category Archives: Python

Save a String to File in Python

A simple way to save a string (or whatever) to a file in Python is: file = open(‘File.txt’, ‘w’) file.write(‘whatever’) file.close()file = open(‘File.txt’, ‘w’) file.write(‘whatever’) file.close() An alternative method that auto-closed the file is: with open(‘File.txt’, ‘w’) as file: file.write(‘whatever’)with open(‘File.txt’, ‘w’) as file: file.write(‘whatever’)

Create a File Name with Current Date & Time in Python

In Python you can get the current date and time like this: import time timestr = time.strftime("%Y-%m-%d_%H-%M-%S") print(timestr)import time timestr = time.strftime("%Y-%m-%d_%H-%M-%S") print(timestr) Here is an example output: 2019-08-11_15-23-022019-08-11_15-23-02 Then you can use timestr variable as file name, i.e: file = open(timestr+’.txt’, ‘w’) file.write(‘whatever’) file.close()file = open(timestr+’.txt’, ‘w’) file.write(‘whatever’) file.close() Or another example below: with […]

Get Current Script Path in Python

Snippet to get current script directory in Python: import os print(os.path.dirname(os.path.realpath(__file__)))import os print(os.path.dirname(os.path.realpath(__file__))) It will output the current Python script path, i.e: /path/to/python/script/path/to/python/script

Python Wildcard Search a String or Array

In Python you can use fnmatch to enable wildcard search: import fnmatchimport fnmatch Wildcard search and array of strings: lst = [‘string1’, ‘testing’, ‘football’]   if fnmatch.filter(lst, ‘th?s’): print(‘Matched’)lst = [‘string1’, ‘testing’, ‘football’] if fnmatch.filter(lst, ‘th?s’): print(‘Matched’) Wildcard search a string: if fnmatch.fnmatch(‘readme.txt’, ‘*.txt’): print(‘Matched’)if fnmatch.fnmatch(‘readme.txt’, ‘*.txt’): print(‘Matched’)

Run Shell Command And Capture Output in Python

To run a shell command and capture the output in Python, use: import subprocess   batcmd="ls"   result = subprocess.check_output(batcmd, shell=True)import subprocess batcmd="ls" result = subprocess.check_output(batcmd, shell=True) With “shell=True” you will get the same behavior as os.system(). To capture the strerr use: result = subprocess.check_output([batcmd], stderr=subprocess.STDOUT)result = subprocess.check_output([batcmd], stderr=subprocess.STDOUT)

Python Iterate over a List in Chunks

Here is a function that iterates a list in chunks: # (in python 2 use xrange() instead of range() to avoid allocating a list) def chunker(seq, size): return (seq[pos:pos + size] for pos in range(0, len(seq), size))# (in python 2 use xrange() instead of range() to avoid allocating a list) def chunker(seq, size): return (seq[pos:pos […]

Run Processes in Parallel in Python

Today I found a nice example to run processes in parallel in python: import os from multiprocessing import Pool     processes = (‘process1.py’, ‘process2.py’, ‘process3.py’)     def run_process(process): os.system(‘python {}’.format(process))     pool = Pool(processes=3) pool.map(run_process, processes)import os from multiprocessing import Pool processes = (‘process1.py’, ‘process2.py’, ‘process3.py’) def run_process(process): os.system(‘python {}’.format(process)) pool = […]

How to Terminate a Python Script

The simplest way is to use quit(), i.e: // do something   quit()// do something quit() Another way is to use sys.exit(), i.e: import sys sys.exit()import sys sys.exit()

Read File Line by Line in Python

Example to read a file line by line in python: testsite_array = [] with open(‘file.txt’) as my_file: for line in my_file: testsite_array.append(line)testsite_array = [] with open(‘file.txt’) as my_file: for line in my_file: testsite_array.append(line) Alternatively, you may want to use f.readlines(): with open(‘file.txt’) as my_file: testsite_array = my_file.readlines()with open(‘file.txt’) as my_file: testsite_array = my_file.readlines()