0

Is there a more concise way of doing the following, e.g. on a single line and without the temporary variable f?

with open('foo.txt', 'w') as f:
    f.write('foobar')

I'm often writing a bunch of files in scripts and this looks ugly, e.g. in one of my test scripts I have the following ugly:

sorted_alembic_schema = sort_lines_without_commas(alembic_schema)
sorted_sqlalchemy_schema = sort_lines_without_commas(sqlalchemy_schema)
if sorted_alembic_schema != sorted_sqlalchemy_schema:
    for file_name, file_contents in [('alembic.schema', alembic_schema),
                                     ('sqlalchemy.schema', sqlalchemy_schema),
                                     ('alembic.schema.sorted', sorted_alembic_schema),
                                     ('sqlalchemy.schema.sorted', sorted_sqlalchemy_schema)]:
        with open(file_name, 'w') as f:
            f.write(file_contents)
    print("""
ERROR: alembic upgrade schema doesn't match sqlalchemy schema; see local files for more info, e.g.

meld sqlalchemy.schema alembic.schema
meld sqlalchemy.schema.sorted alembic.schema.sorted

FAIL"""
          )
3
  • 1
    No, there is no other more concise way then what you are already doing with with open('foo.txt', 'w') as f: f.write('foobar') and I do not think this is ugly at all. The rest of your code may be harder to read but that is a matter of preference. Personally I think your code is more difficult to read because: 1) you define that four-line list in the loop; and 2) you use many excessively long variable and function names. Commented Nov 12, 2017 at 3:58
  • @AGNGazer lol, you are right that my ugly code has little to do with the two line file writing, maybe I was looking for a scape goat Commented Nov 12, 2017 at 6:01
  • @wp78de This question is not a duplicate of stackoverflow.com/questions/5214578/… ; please don't close. This differs because it is explicitly asking if there is a more concise way to write this while the other question essentially asks the idiomatic way to write this. Commented Nov 12, 2017 at 6:02

4 Answers 4

1

The with keyword is already a compression which opens, flushes, and closes something. There’s no one word compression of that statement.

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

Comments

1

Ugly code cannot be avoided all the time, and ugly code is not necessarily bad code. However, there is certainly room for improvement.

Regarding file writing: Extract a method for it

def StringToFile(file_path, content):
    with open(file_path, 'w') as fp:
        fp.write(content)

or use an external library function like numpy.savetext:

np.savetxt('test.out', x, delimiter=',')   # X is an array

Comments

0

The temporary variable f represents the open file object. The with block takes care of opening the file and locking it for writing (os-level). The write-lock is released when the with block closes. I think the way you have it is perfect.

Comments

0

You could define a function that handles the writing in a single line, but it would just be an encapsulation of what you have already written.

def quick_write(file_path, content):
    with open(file_path, 'w') as fp:
        fp.write(content)

In your code, it would replace the 2 line with-statement:

if sorted_alembic_schema != sorted_sqlalchemy_schema:
    for file_name, file_contents in [...]:
        quick_write(file_name, file_contents)

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.