10/03/18 1 Computational Physics Laboratory Python scripting LECTURE 5 PRACTICE ON SCRIPTING Outline • Practice on exam tests
10/03/18
1
Computational Physics Laboratory���Python scripting
LECTURE 5 PRACTICE ON SCRIPTING
Outline • Practice on exam tests
10/03/18
2
Python
file_input = open("input-base", "r")str_input = file_input.read()file_input.close()for i in range(10): modified_input = str_input.replace("cut",str(i+1)) new_input = open("input"+str(i+1), "w") new_input.write(modified_input) new_input.close()
Open the file Put its content in a string Close the file Loop on i: Modify the string with .replace method Open i-th output file Write in the output file Close the output file
10/03/18
3
Python
import sys
if len(sys.argv) < 3: print("Usage: python svolgimento.py word text_file") sys.exit(2)
word = sys.argv[1]textfile = sys.argv[2]f = open(textfile, "r")content = f.read()f.close()found = Falseif word in content: print(word + " is in " + textfile) found = True
if not found: print(word + " is not in " + textfile)
Note: Use sys module to pass the string to search for and the file
10/03/18
4
Python
import os
list_res = [x for x in os.listdir() if x.endswith(".res")]for filename in list_res: fin = open(filename, "r") fileout = os.path.splitext(filename)[0]+".dat" fout = open(fileout, "w") Nlines = 0 for line in fin.readlines(): Nlines += 1 if Nlines >= 6 and Nlines <=105: fout.write(line) fin.close() fout.close()
Note 2: Used a list-comprehension to create a list with .res files in the script directory
Note 1: import osf = "nomefile.txt"splitted = os.path.splitext(f)print(type(splitted))print(splitted)
Result: >>><class 'tuple'>('nomefile', '.txt')>>>
10/03/18
5
Python
import fnmatchimport ospattern = "*.tex"
files = os.listdir('./lettere')for name in files: if fnmatch.fnmatch(name, pattern): dirname = name.strip(".tex") os.mkdir(dirname) os.system("cp lettere/" + name + " " + dirname + "/" + name)
os.chdir(dirname) file_letter = open(name, "r") letter = file_letter.read() file_letter.close() os.system("rm " + name) modified_letter = letter.replace("15","04")
modified_letter = modified_letter.replace("03","05") new_letter = open(name, "w") new_letter.write(modified_letter) new_letter.close() os.system("latex " + name) os.system("dvipdf " + dirname + ".dvi") os.system("rm " + name)
os.system("rm " + dirname + ".dvi") os.system("rm " + dirname + ".aux") os.system("rm " + dirname + ".log") os.chdir("../")
import fnmatchimport os
for file in os.listdir(): if fnmatch.fnmatch(file, '*.txt'): print(file)
Result example: >>>textfile.txt>>>
10/03/18
6
Python
import osos.chdir("./dati")list_pdat = [x for x in os.listdir() if x.endswith(".dat")]file_sez = open("xsec.res", "w") #il file deve contenere le prime colonne di ogni file.dat
sezioni = [] #creo una lista vuota, ogni elemento sarà una riga del file "xsec.res”readfile = 0for filename in list_pdat: #ciclo sui files
fin = open(filename, "r") fileout = os.path.splitext(filename)[0]+".res" fout = open(fileout, "w") readline = 0
for line in fin.readlines(): #ciclo sulle linee nel file list_data = line.split() if readfile==0: # N.componenti = N.linee dei files.dat
sezioni.append(list_data[0]) #la lista contiene la prima colonna del file else: #ho già la lista con le corrette dimensioni sezioni[readline] += "\t"+list_data[0] readline += 1
stringa = "" for i in range(len(list_data)): if i>0: stringa += list_data[i]+"\t"
fout.write(stringa+"\n") readfile = 1 fin.close()
fout.close() os.system("rm "+filename)for i in range(readline): file_sez.write(sezioni[i]+"\n")
file_sez.close()
10/03/18
7
Python
import osimport sys
def nonblank_lines(f): for l in f: line = l.rstrip() if line: yield line
if len(sys.argv) < 2: print("Pass me a process, please!") sys.exit(2)
process = sys.argv[1]os.system("ps -xc > processes.txt")
file_proc = open("processes.txt", "r")found = Falsefor line in nonblank_lines(file_proc): if process in line: info = line.split(" ") print("The PID of process: " + process + " is: " + info[2]) found = True
if not found: print("There is no process called: " + process)os.system("rm processes.txt")file_proc.close()
10/03/18
8
Python
def nonblank_lines(f): for l in f: line = l.rstrip()
if line: yield linetitles = []names = []fnames = []Nguys = 0
file_names = open("elenco.txt", "r")for line in nonblank_lines(file_names): attribute = line.split(" ") titles.append(attribute[0]) names.append(attribute[1]) fnames.append(attribute[2])
Nguys += 1file_letter = open("lettera.txt", "r")letter = file_letter.read()file_letter.close()for i in range(Nguys): modified_letter = letter.replace("FAMILYNAME",fnames[i]) modified_letter = modified_letter.replace("NAME",names[i])
modified_letter = modified_letter.replace("TITLE",titles[i]) new_letter = open(fnames[i]+"_LETTER.txt", "w") new_letter.write(modified_letter) new_letter.close()