Writing a List to a File With Python, With Newlines

How to write a list to a file with newlines in Python3

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.

Writing a list to a file with Python, with newlines

Use a loop:

with open('your_file.txt', 'w') as f:
for line in lines:
f.write(f"{line}\n")

For Python <3.6:

with open('your_file.txt', 'w') as f:
for line in lines:
f.write("%s\n" % line)

For Python 2, one may also use:

with open('your_file.txt', 'w') as f:
for line in lines:
print >> f, line

If you're keen on a single function call, at least remove the square brackets [], so that the strings to be printed get made one at a time (a genexp rather than a listcomp) -- no reason to take up all the memory required to materialize the whole list of strings.

write list of lists to file but each tuple has to be on a new line, using python

I really don't any reason here to use json.dumps. You can just use a normal for loop:

a = [
[93.400000000000006, "high"],
[98.600000000000009, 99.0, "high"],
[111.60000000000001, 112.5, "high"]
]

with open('sample.txt', 'a') as outfile:
for sublist in a:
outfile.write('{}\n'.format(sublist))

The above code produces the output:

[93.400000000000006, 'high']
[98.600000000000009, 99.0, 'high']
[111.60000000000001, 112.5, 'high']

Write each element of a list on a newline on a text file in Python

If you're writing text, you shouldn't use the "b" mode:

with open(filename, mode="w") as outfile: 
# Here ---------------^

Writing string to a file on a new line every time

Use "\n":

file.write("My String\n")

See the Python manual for reference.

How can I write list of strings to file, adding newlines?

Change

data.write(c + n)

to

data.write("%s%s\n" % (c, n))

I can't add a new line when writing a file in Python

I think what you want is appending to the file, instead of writing (truncating the file if it already exists):

    # ...

else:
taken.append(file_name)
file = open('logs.txt', 'a+') # 'a+' mode instead of 'w' mode
file.write(file_name + '\n')
file.close()
# ...

Refer to document.

How to write a list to a new line in a file for Python

You can use f.write('\n') to add a new line to the file.

I.E. make your code into:

import json
f = open("Troubleshooting.txt","a")
f.write('\n')
json.dump(problem,f)
f.close()


Related Topics



Leave a reply



Submit