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"""
          )
JDiMatteo
  • 12,022
  • 5
  • 54
  • 65
  • 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. – AGN Gazer Nov 12 '17 at 03: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 – JDiMatteo Nov 12 '17 at 06:01
  • @wp78de This question is not a duplicate of https://stackoverflow.com/questions/5214578/python-print-string-to-text-file ; 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. – JDiMatteo Nov 12 '17 at 06:02

4 Answers4

1

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

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
wp78de
  • 18,207
  • 7
  • 43
  • 71
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.

soundstripe
  • 1,454
  • 11
  • 19
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)
James
  • 32,991
  • 4
  • 47
  • 70