1

I want to take lines of text from a .txt file and copy it to the bottom of an existing word doc. i have something that does this from one text file to another but the overall goal is to copy it to the bottom of a word document for a report.

I am using python 2.6 and currently have

with open('Error.txt', 'w') as f1:
    for line in open('2_axis_histogram.txt'):
        if line.startswith('Error'):
            f1.write(line)
        else:
            f1.write("No Error ")
    f1.close()

I have no idea about how i could then transfer this to word.

Also, when there is no error and the else condition is used, it prints out the "No Error" loads of times whereas i just need it to print that statement once.

Alexis Pigeon
  • 7,423
  • 11
  • 39
  • 44
manish449
  • 511
  • 3
  • 11
  • 17
  • Have you checked Google? Google lead me here: http://stackoverflow.com/questions/1035183/how-can-i-create-a-word-document-using-python which, while a slightly different question, it offers the answer to yours. – Pete Jul 08 '13 at 13:27
  • 'write' only happens once it prints it out multiple times because it's happening for each line. Also, you're closing your file mid-stream...and you don't need to close when you use 'with' – Chris Pfohl Jul 08 '13 at 13:30
  • 1
    Note, use 4 spaces for tabs when writing python. – Chris Pfohl Jul 08 '13 at 13:31

3 Answers3

1

first question : use Google, or StackOverflow search : Reading/Writing MS Word files in Python

second question : get your ´No Error´ display out of the loop...

Community
  • 1
  • 1
Laurent S.
  • 6,816
  • 2
  • 28
  • 40
0

You should look into https://github.com/mikemaccana/python-docx

This is a module that creates, reads and writes Microsoft Office Word 2007 docx files.

Atra Azami
  • 2,215
  • 1
  • 14
  • 12
  • i have tried intsalling the module but no joy it says cant fine the docx module but i can see it any ideas> – manish449 Jul 08 '13 at 13:56
0

To get rid of the extraneous "No Error" messages, put the else statement into the for loop, not the if because the latter is checked on every line:

with open('Error.txt', 'w') as f1:
    for line in open('2_axis_histogram.txt'):
        if line.startswith('Error'):
            f1.write(line)
            break            # Exit the for loop, bypassing the else statement
    else:                    # Only executed if the for loop finishes
        f1.write("No Error ")           

Also, no need to close f1 - the with statement already is taking care of that for you.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • @martineau: There are already answers that handle the other part - I don't like redundancy much. Well, that's what I get for answering a double question :) – Tim Pietzcker Jul 08 '13 at 13:37