Finger Bruno
Finger Bruno

Reputation: 39

how can I export a list to txt without commas and quotes

fruits = ['bananas', 'apples', 'oranges', 'strawberry']
with open("fruits_text.txt", 'w') as totxt_file:
    totxt_file.write(str(fruits)+'\n')

The "\n" in code above doesnt work, when I run it here is what I got

['bananas', 'apples', 'oranges', 'strawberry']

How can I export it without commas and quotes? like this

bananas
apples 
oranges
strawberry 

Upvotes: 0

Views: 1127

Answers (4)

blhsing
blhsing

Reputation: 106881

You can unpack the list as arguments for the print function, which supports a file keyword argument for file output. Use the sep keyword argument to separate each record by newlines:

with open("fruits_text.txt", 'w') as totxt_file:
    print(*fruits, sep='\n', file=totxt_file)

Upvotes: 0

Alain T.
Alain T.

Reputation: 42133

You could use writelines() with a comprehension to add an end of line to each string:

fruits = ['bananas', 'apples', 'oranges', 'strawberry']
with open("fruits_text.txt", 'w') as totxt_file:
    totxt_file.writelines(f+"\n" for f in fruits)

Upvotes: 0

Chris
Chris

Reputation: 29742

One way using str.join:

fruits = ['bananas', 'apples', 'oranges', 'strawberry']
with open("fruits_text.txt", 'w') as totxt_file:
    totxt_file.write("\n".join(fruits))

Note that this doesn't insert a line separator (\n here) at the very end of the last line, which might be problematic in some cases.

Output:

# cat fruits_text.txt
bananas
apples
oranges
strawberry

Upvotes: 3

Jan Wilamowski
Jan Wilamowski

Reputation: 3598

Iterate over all items and write them separately:

fruits = ['bananas', 'apples', 'oranges', 'strawberry']
with open("fruits_text.txt", 'w') as totxt_file:
    for fruit in fruits:
        totxt_file.write(fruit + '\n')

Upvotes: 2

Related Questions