-1

i i only want to save specific print result of every execution of code on text file

i try with

if to,from_addr != '0x':
            print(To:,From:)
            os.system(f'echo {To:} {From:} >> output.txt')

but everytime fail, also I also want that every time a new result appears, a new line is added and not replace the later output

enter image description here

i try with

with open("Output.txt", "w") as text_file:
    print(f"To:" "From:" {to} {from_addr}", file=text_file)
3
  • from is a reserved word so I would not use that a variable name. I have a hard time understanding what you are asking. Maybe give us sample input (as text), and expected output? Also, I can't tell if the above is incomplete snippets or if you haven't extract data from input into variables yet. Commented Jan 23, 2023 at 7:43
  • @AllanWind exactly, also print is not the function to write to a file, you need to used the file pointer text_file you defined when using context manager. Commented Jan 23, 2023 at 7:46
  • @Gameplay. print can write to a file if you specify file=<handler> as parameter. By default, print use the stdout handler. => file: a file-like object (stream); defaults to the current sys.stdout. (documentation) Commented Jan 23, 2023 at 7:53

1 Answer 1

1

Use append mode and fix f-strings:

to = 'destination'
from_addr = 'source'

# Use append mode
with open("Output.txt", "a") as text_file:
    if not (to.startswith('0x') or from_addr.startswith('0x')):
        print(f"To: {to}\nFrom: {from_addr}", file=text_file)
Sign up to request clarification or add additional context in comments.

2 Comments

Does it do both, printing and saving?
@cards. It prints the output to file handler (saving)

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.