• Python

Filed under:

I quite like Python, but it goes infrequently used, sometimes for long stretches of time. I often forget standard library, syntax, and the ecosystem. So - some notes:



Used for in exception handling cases to clean up your code:

# 1) without using with statement
file = open('file_path', 'w')
file.write('hello world !')  # an exception here might cause the file to improperly close / not close at all.

# 2) without using with statement
# this is fine code, but just not as clean.
file = open('file_path', 'w')
    file.write('hello world')

# using with statement
with open('file_path', 'w') as file:
    file.write('hello world !')

File operations

Open a file

f = open("demofile.txt", "r")

Open a JSON file:

import json

with open('data.txt') as json_file:
    data = json.load(json_file)
    for p in data['people']:
        print('Name: ' + p['name'])
        print('Website: ' + p['website'])
        print('From: ' + p['from'])

Write a json file

with open('data.txt', 'w') as outfile:
    json.dump(data, outfile)

Quick file rename snippet.

#!/usr/bin/env python3
import glob
import os

audio_files = (glob.glob("*.wav")) # example: grab all wav files.
new_name  = input("input new name: ")

for f in audio_files:
    split_name = os.path.splitext(f)[0] # get the name of the file
    name = split_name[0]                # split tuple to get the original name if needed.
    ext = split_name[1]                 # keep the extension
    os.rename(f, new_name + name + ext) # in this case, we're prepending a custom input with the original name