0

I have a log file where i'm fetching only the desired output and into two different variables and when i run the code it prints currently but i need both the variable data written into another file called file1. I have the raw code sample which i tried working with print but not getting the idea about writing it into a file.

with open("testfile","r") as fh:
    for line in fh:
        if "ping" in line:
            if HOST != "NA" and Flag:
                mydata1 = hostname  

        elif HOST != "NA" and Flag and HOST not in mydata1:
            mydata2 = logname
            mydata3 = open('file1', 'w')
            mydata3.write(mydata1,mydata2)
    mydata3.close()
#print(mydata1,mydata2)
4
  • This line might be causing some problem lif HOST != "NA" and Flag and HOST not in mydata1: Commented May 28, 2018 at 18:00
  • Your code is really confusing. What is hostname or logname? Please make a reproducible example. Also, there is the logging module designed for logging; is there a reason you're not using that? Commented May 28, 2018 at 18:00
  • @Rakesh, it works perfectly while printing , however i'm not sure about my new file writing if thats correct or not. Commented May 28, 2018 at 18:03
  • @roganjosh, as i said raw code becuae it has some company data hence i snipped the real data and Just kept sample for the sake of variable names which shows it has data. However its not system logging , its kind of slef created log data where we don't hve option to use logging module. Commented May 28, 2018 at 18:06

1 Answer 1

1

Try using str.format:

Ex:

with open("testfile","r") as fh:
    for line in fh:
        if "ping" in line:
            if HOST != "NA" and Flag:
                mydata1 = hostname

        elif HOST != "NA" and Flag == True and HOST not in mydata1:
            mydata2 = logname
            mydata3 = open('file1', 'w')
            mydata3.write("{0} {1}".format(mydata1,mydata2))
    mydata3.close()
Sign up to request clarification or add additional context in comments.

7 Comments

let me try the provided.
it would be easier, or at least for me, to put mydata1 + " " + mydata2, or if they use 3.6, f"{mydata1} {mydata}"
@IvánC.. You can use that also. I am just used to str.format :)
@IvánC.. Would you be able to provide the way which you are talking about in my case above, i'm sorry for my golden fish memory syndrom :)
@Rakesh, i was Just adjusting format tofit my code and now it works with using str.format, Great thnx. Would you be able to explain the logic behind.
|

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.