Last active
August 14, 2020 10:52
-
-
Save phistep/f0f46eab4189d1d0760b9377eae0840e to your computer and use it in GitHub Desktop.
Python glob example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/python3 | |
# run as | |
# python3 read_dir.py test_dir | |
import os | |
import sys | |
import glob | |
import numpy as np | |
import matplotlib.pyplot as plt | |
file_dir = sys.argv[1] | |
file_template = 'gap{}.dat' | |
# setup dummy data | |
if not os.path.exists(file_dir): | |
os.mkdir(file_dir) | |
for n in range(20): | |
with open(os.path.join(file_dir, file_template.format(n)), 'w') as f: | |
for x in range(10): | |
f.write(f"{x} {n*x}\n") | |
# read and plot data | |
plt.figure() | |
plt.title("Dummy Data") | |
plt.xlabel('x') | |
# https://docs.python.org/3/library/glob.html | |
# for data_file in glob.glob("dir/gap*.dat") | |
for data_file in glob.glob(os.path.join(file_dir, file_template.format('*'))): | |
x, fx = np.loadtxt(data_file, unpack=True) | |
plt.plot(x, fx, 'x-', label=data_file) | |
plt.legend() | |
plt.xlabel('x') | |
plt.ylabel('f(x)') | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment