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.

3
  • Have you checked Google? Google lead me here: stackoverflow.com/questions/1035183/… which, while a slightly different question, it offers the answer to yours. Commented Jul 8, 2013 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' Commented Jul 8, 2013 at 13:30
  • 1
    Note, use 4 spaces for tabs when writing python. Commented Jul 8, 2013 at 13:31

3 Answers 3

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...

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

i have tried intsalling the module but no joy it says cant fine the docx module but i can see it any ideas>
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.

1 Comment

@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 :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.