I need to write my Python shell to an output text file. I have some of it written into an output text file but all I need is to now add the number of lines and numbers in each line to my output text file.
I have tried to add another for loop outside the for loop. I've tried putting it inside the for loop and it was just complicated.
Text file list of numbers:
1.0, 1.12, 1.123 1.0,1.12,1.123 1 Code:
import re index = 0 comma_string = ', ' outfile = "output2.txt" wp_string = " White Space Detected" tab_string = " tab detected" mc_string = " Missing carriage return" ne_string = " No Error" baconFile = open(outfile,"wt") with open("Version2_file.txt", 'r') as f: for line in f: flag = 0 carrera = "" index = index +1 print("Line {}: ".format(index)) baconFile.write("Line {}: ".format(index)) if " " in line: #checking for whitespace carrera = carrera + wp_string + comma_string + carrera flag = 1 a = 1 if "\t" in line: #checking for tabs return carrera = carrera + tab_string + comma_string + carrera flag = 1 if '\n' not in line: carrera = carrera + mc_string + ne_string + carrera flag = 1 if flag == 0: #checking if no error is true by setting flag equal to zero carrera = ne_string print('\t'.join(str(len(g)) for g in re.findall(r'\d+\.?(\d+)?', line ))) print (carrera) baconFile.write('\t'.join(str(len(g)) for g in re.findall(r'\d+\.?(\d+)?', line ) )) baconFile.write(carrera + "\n") with open("Version2_file.txt", 'r') as f: content = f.readlines() print('Number of Lines: {}'.format(len(content))) for i in range(len(content)): print('Numbers in Line {}: {}'.format(i+1, len(content[i].split(',')))) baconFile.write('Number of lines: {}'.format(len(content))) baconFile.write('Numbers in Line {}: {}'.format(i+1, len(content[i].split(',')))) baconFile.close() Expected to write in output file:
Line 1: 1 2 3 Tab detected, whitespace detected Line 2: 1 2 3 No error Line 3: 1 Missing carriage return No error Number of Lines: 3 Numbers in Line 1: 3 Numbers in Line 2: 3 Numbers in Line 3: 1 Actual from output file:
Line 1: 1 3 2White Space Detected, tab detected, White Space Detected, Line 2: 1 3 2No Error Line 3: 0Missing carriage returnNo Error Number of lines: 3Numbers in Line 1: 3Number of lines: 3Numbers in Line 2: 3Numb
open()the output file in"w"mode, and callfile.write()instead of callingprint().print()andwrite()(the former adds a newline at the end automatically).