It140 Mod 6.docx - File Handling 4 3 Challenge reading a...

This preview shows page 1 - 5 out of 10 pages.

File Handling4. 3. Challenge: reading a text file# Load our command line argumentsimport sysP= sys.argv[1]S= sys.argv[2]# Your code goes hereimport refile1 = open(P)data = file1.read()results = re.findall(S, data)print (len(results))4. 5. Challenge: writing a text file# Get the filepath from the command lineimport sysI= sys.argv[1] O= sys.argv[2] S= sys.argv[3]T= sys.argv[4]# Your code goes herewith open(O,'w') as out:with open(I, 'r') as f:for cats in f:out.write(cats.replace(S,T))
5. 3. Challenge: Fixed Length Records# Get the filepath from the command lineimport sysP= sys.argv[1] F= sys.argv[2]L= sys.argv[3]B= sys.argv[4]# Your Code Goes Herefiles = open(P, 'r')data = files.read()files.close()recordlist = []while (len(data) >0):record = []record.append(data[0:16])record.append(data[16:32])record.append(data[32:40])recordlist.append(record)data = data[40:]output = ''for i in range(0, len(recordlist)):thisRecord = recordlist[i]if (thisRecord[0].strip() == F and thisRecord[1].strip() == L):
thisRecord[2] = Boutput += thisRecord[0] + thisRecord[1] + thisRecord[2]f = open(P, 'w')f.write(output)f.close()5. 5. Challenge: variable length records# Get the filepath from the command lineimport sysP= sys.argv[1] F= sys.argv[2]L= sys.argv[3]B= sys.argv[4]# ----------------------------------------------------------------# # Our Helper functions:# # ----------------------------------------------------------------## Loads the file at filepath # Returns a 2d array with the data# def load2dArrayFromFile(filepath):with open(filepath, 'r') as rfile:totallines = rfile.read().split('\n')while '' in totallines:
totallines.remove('')loadedArray = [eachline.split('|') for eachline in totallines]return loadedArray

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture