0

Can i know how i can write obtained result to a File in python. For example, Below code snippet check for state. If it pass it prints pass otherwise fail.

if generalTools.waitAppear('State2.png', '25') == False:
    testData.reportFail("Fail: TestCase Fail")
else:
    testData.reportPass("PASS: TestCase Pass")  

So, here i want to push result to a file instead of printing.

First, it has to check whether the file exists or not .If it exists, it has to clear the content and write to that file. If file doesn't exists. it has to create new file and it has to write. Can any1 give me some idea how i can do that.

4
  • You don't need any of those checks, open file like with open('data.txt', 'w') as fout: 'w' will truncate it for you Commented May 7, 2013 at 9:48
  • 1
    docs.python.org/2/tutorial/… Commented May 7, 2013 at 9:49
  • and one more doubt. If i place this line in different file...does it clean up everytime? Commented May 7, 2013 at 10:11
  • I think the question is a little misleading. Existing file is ambiguous whether you want delete file and create new one or you want to append to a file. My suggestion is to change question to something like How to write result to a file (with overriding it if exists). Commented May 7, 2013 at 10:14

1 Answer 1

3

You don't have to do anything special. Use the following code:

with open('workfile', 'w') as fout:
    fout.write(result)

Opening a file in 'write' mode creates it if it doesn't exist, or blanks it and starts again from scratch.

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

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.