3

I know that in Python the preferred mechanism for splitting code over multiple lines is to use implicit continuation with constructs like parentheses, etc. Alternatively, backslashes can also be used.

However, I'm having issues with a long write statement (example code):

f1 = some_file_name
with open(f1,'w') as o:
    # file in csv format
    # want to write a header before data
    o.write("column1 header,column2 header,column3 header,column4 header,etc")

If I break the line, Python complains ('EOL while scanning string literal'):

    o.write("column1 header,column2 header,column3 header, # complains
        column4 header,column5 header")

If I use a backslash and try to keep the same indent level the extra space is included in the file header:

    o.write("column1 header,column2 header,column3 header,\
        column4 header,column5 header")

    # file contents:
    column1 header,column2 header,column3 header,      column4 header,column5 header

For now I have a backslash with the remaining string starting from the very beginning of the next line, but the code looks messy this way.

I'm probably missing something very obvious, but what is the preferred way of dealing with long strings when writing to files like this?

1 Answer 1

4

Python lets you do the following:

o.write("column1 header,column2 header,column3 header,"
        "column4 header,column5 header")

This creates one string without any newlines by concatenating these strings.

The reason why the backslash fails to provide the correct result is because the whitespace inside the string matters:

o.write("column1 header,column2 header,column3 header,\
     column4 header,column5 header")
^^^^^
These spaces end up in the string.
Sign up to request clarification or add additional context in comments.

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.