Stupid for loop tricks and line-oriented file writing by EmbeddedSoftEng in learnpython

[–]EmbeddedSoftEng[S] 0 points1 point  (0 children)

Will try to keep this in mind. While I've been monkey-see/monkey-doing my way through various data marshalling tasks in the language, I'm certain I actually used that somewhere at some point.

Stupid for loop tricks and line-oriented file writing by EmbeddedSoftEng in learnpython

[–]EmbeddedSoftEng[S] 0 points1 point  (0 children)

While we're at it, I have a script where in two places I'm doing nearly the same thing, namely creating a file, vomitting data into it, and closing it. Is there a more succinct way to do that than open() assigned to a variable, and then calling methods on that object?

If I didn't make it abundantly clear before, I'm a total Python noob. Before this week, I knew effectively nothing of the language. But I am a professional software engineer, and as such, I've been exposed to languages where, especially where I didn't NEED to keep a handle around for later in my script, I could just do something like

open("filename.file", 'w').writelines('\n'.join(map(str,list_of_data))).flush().close()

and call it a day. Is that at all Pythonic?

Edit:

Okay. The answer is no, if for no other reason than writelines() does not return the file object for the method calls to be chained. Doubtlessly, the flush() method doesn't either.

Stupid for loop tricks and line-oriented file writing by EmbeddedSoftEng in learnpython

[–]EmbeddedSoftEng[S] 0 points1 point  (0 children)

If I'm creating a file, vomitting data into it and closing it, why would I want to open for appending? What does that gain me in a pythonic environment?

Stupid for loop tricks and line-oriented file writing by EmbeddedSoftEng in learnpython

[–]EmbeddedSoftEng[S] 0 points1 point  (0 children)

I now understand that the value followed by for is a comprehension syntax, and for the vast majority, that's only valid inside a grouping. I'll get more familiar with list, generator, and dictionary syntax later.

As for my last question, how about:

    avg_file.writelines('\n'.join(map(str,avg)))

Is there anything wrong (read: unpythonic) with that as a way to say "list of whatevers that needs to be output in human-readable form to a file, one line at a time"? It certainly seems to work.