0

How can I write the following using Python with -c to execute a one-liner loop?

import json
dictionary = {"one":"two", "three":"four" }
with open("data.txt", "r+") as f:
    data = f.read()
    for key in dictionary.keys():
        data = data.replace(key, dictionary[key])
    f.seek(0)
    f.write(data)
    f.truncate()

I tried:

python3 -c $'import json;dictionary = dictionary = {"one":"two", "three":"four" }\nwith open("data.txt", "r+") as f: f.seek(0); data = f.read()\nfor key in dictionary.keys(): data = data.replace(key, dictionary[key]); f.write(data)'

and got:

Traceback (most recent call last):
  File "<string>", line 3, in <module>
ValueError: I/O operation on closed file.
khelwood
  • 55,782
  • 14
  • 81
  • 108
  • 1
    Does this answer your question? [How can I put multiple statements in one line?](https://stackoverflow.com/questions/6167127/how-can-i-put-multiple-statements-in-one-line). Check the second most upvoted answer. – danzel artamadja May 04 '23 at 00:53
  • 1
    Your code works for me if I fix the indentation and order of statements: https://pastebin.com/raw/7GkUPEH9 – Nick ODell May 04 '23 at 01:01
  • The comment by Nick ODell is right. I just ask myself, **why** you want to do it. Python is very picky about intdentation, and in addition, squeezing everything into a single line makes the code hard to maintain. Are you perahaps intending to put this into a crontab entry? – user1934428 May 04 '23 at 10:18

0 Answers0