1

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

4
  • 1
    the python shell prints out what is expected but it does not write it all to anoutput file Commented Jul 2, 2019 at 23:30
  • 1
    If you want to save the output produced by the second loop, you need to open() the output file in "w" mode, and call file.write() instead of calling print(). Commented Jul 2, 2019 at 23:56
  • 1
    I got it, thanks! Do I need to add a + "\n" inside my baconFile.write so it can separate the Numbers in line as a carriage return Commented Jul 3, 2019 at 17:03
  • 1
    Yeah, that's one of several differences between print() and write() (the former adds a newline at the end automatically). Commented Jul 3, 2019 at 17:08

2 Answers 2

1

You have closed baconFile in the first open block, but do not open it again in the second open block. Additionally, you never write to baconFile in the second open block, which makes sense considering you've not opened it there, but then you can't expect to have written to it. It seems you simply forgot to add some write statements. Perhaps you confused write with print. Add those write statements in and you should be golden.

baconFile = open(outfile,"wt")
with open("Version2_file.txt", 'r') as f:
    for line in f:                       
        # ... line processing ...
        baconFile.write(...)  # line format info here
    # baconFile.close()  ## <-- move this
with open("Version2_file.txt", 'r') as f:
    content = f.readlines()
    baconFile.write(...)  # number of lines info here
    for i in range(len(content)):
        baconFile.write(...)  # numbers in each line info here
baconFile.close()  # <-- over here
Sign up to request clarification or add additional context in comments.

2 Comments

I got it, thanks! If I add a + "\n" inside my baconFile.write will it separate the Numbers in line to a new line?
Yep. print adds a newline character to the end of the output unless otherwise specified: print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False). In contrast, write does not.
0

Here's a useful trick you can use to make print statements send their output to a specified file instead of the screen (i.e. stdout):

from contextlib import contextmanager
import os
import sys


@contextmanager
def redirect_stdout(target_file):
    save_stdout = sys.stdout
    sys.stdout = target_file
    yield
    sys.stdout = save_stdout

# Sample usage
with open('output2.txt', 'wt') as target_file:
    with redirect_stdout(target_file):
        print 'hello world'
        print 'testing', (1, 2, 3)

print 'done'  # Won't be redirected.

Contents of output2.txt file after running the above:

hello world
testing (1, 2, 3)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.