I'm trying to write an array (list?) to a text file using Python 3. Currently I have:
def save_to_file(*text): with open('/path/to/filename.txt', mode='wt', encoding='utf-8') as myfile: for lines in text: print(lines, file = myfile) myfile.close
This writes what looks like the array straight to the text file, i.e.,
['element1', 'element2', 'element3'] username@machine:/path$
What I'm looking to do is create the file with
element1 element2 element3 username@machine:/path$
I've tried different ways to loop through and append a "\n" but it seems that the write is dumping the array in one operation. The question is similar to How to write list of strings to file, adding newlines? but the syntax looked like it was for Python 2? When I tried a modified version of it:
def save_to_file(*text): myfile = open('/path/to/filename.txt', mode='wt', encoding='utf-8') for lines in text: myfile.write(lines) myfile.close
...the Python shell gives "TypeError: must be str, not list" which I think is because of changes between Python2 and Python 3. What am I missing to get each element on a newline?
EDIT: Thank you to @agf and @arafangion; combining what both of you wrote, I came up with:
def save_to_file(text): with open('/path/to/filename.txt', mode='wt', encoding='utf-8') as myfile: myfile.write('\n'.join(text)) myfile.write('\n')
It looks like I had part of the issue with "*text" (I had read that expands arguments but it didn't click until you wrote that [element] was becoming [[element]] that I was getting a str-not-list type error; I kept thinking I needed to tell the definition that it was getting a list/array passed to it and that just stating "test" would be a string.) It worked once I changed it to just text and used myfile.write with join, and the additional \n puts in the final newline at the end of the file.
A common approach to write the elements of a list to a file using Python is to first loop through the elements of the list using a for loop. Then use a file object to write every element of the list to a file as part of each loop iteration. The file object needs to be opened in write mode.
Specifically, the expression print(*my_list, sep=', ') will print the list elements without brackets and with a comma between subsequent list elements.
myfile.close
-- get rid of that where you use with
. with
automatically closes myfile
, and you have to call close
like close()
anyway for it to do anything when you're not using with
. You should just always use with
on Python 3.
with open('/path/to/filename.txt', mode='wt', encoding='utf-8') as myfile: myfile.write('\n'.join(lines))
Don't use print
to write to files -- use file.write
. In this case, you want to write some lines with line breaks in between, so you can just join the lines with '\n'.join(lines)
and write the string that is created directly to the file.
If the elements of lines
aren't strings, try:
myfile.write('\n'.join(str(line) for line in lines))
to convert them first.
Your second version doesn't work for a different reason. If you pass
['element1', 'element2', 'element3']
to
def save_to_file(*text):
it will become
[['element1', 'element2', 'element3']]
because the *
puts each argument it gets into a list, even if what you pass is already a list.
If you want to support passing multiple lists, and still write them one after another, do
def save_to_file(*text): with open('/path/to/filename.txt', mode='wt', encoding='utf-8') as myfile: for lines in text: myfile.write('\n'.join(str(line) for line in lines)) myfile.write('\n')
or, for just one list, get rid of the *
and do what I did above.
Edit: @Arafangion is right, you should probably just use b
instead of t
for writing to your files. That way, you don't have to worry about the different ways different platforms handle newlines.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With