如何在没有逗号和引号的情况下将列表导出到 txt
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')
上面代码中的“\n”不起作用,当我运行这就是我得到的
['bananas', 'apples', 'oranges', 'strawberry']
如何在没有逗号和引号的情况下导出它?像这样
bananas
apples
oranges
strawberry
遍历所有项目并单独编写:
fruits = ['bananas', 'apples', 'oranges', 'strawberry']
with open("fruits_text.txt", 'w') as totxt_file:
for fruit in fruits:
totxt_file.write(fruit + '\n')
使用str.join
的一种方式:
fruits = ['bananas', 'apples', 'oranges', 'strawberry']
with open("fruits_text.txt", 'w') as totxt_file:
totxt_file.write("\n".join(fruits))
请注意,这不会在最后一行的末尾插入行分隔符(此处为\n
),这在某些情况下可能会出现问题。
输出:
# cat fruits_text.txt
bananas
apples
oranges
strawberry
您可以将列表解压缩为 print
函数的参数,该函数支持文件输出的 file
关键字参数。使用 sep
关键字参数以换行符分隔每条记录:
with open("fruits_text.txt", 'w') as totxt_file:
print(*fruits, sep='\n', file=totxt_file)
您可以使用带有理解力的 writelines() 为每个字符串添加行尾:
fruits = ['bananas', 'apples', 'oranges', 'strawberry']
with open("fruits_text.txt", 'w') as totxt_file:
totxt_file.writelines(f+"\n" for f in fruits)
fruits = ['bananas', 'apples', 'oranges', 'strawberry']
with open("fruits_text.txt", 'w') as totxt_file:
totxt_file.write(str(fruits)+'\n')
上面代码中的“\n”不起作用,当我运行这就是我得到的
['bananas', 'apples', 'oranges', 'strawberry']
如何在没有逗号和引号的情况下导出它?像这样
bananas
apples
oranges
strawberry
遍历所有项目并单独编写:
fruits = ['bananas', 'apples', 'oranges', 'strawberry']
with open("fruits_text.txt", 'w') as totxt_file:
for fruit in fruits:
totxt_file.write(fruit + '\n')
使用str.join
的一种方式:
fruits = ['bananas', 'apples', 'oranges', 'strawberry']
with open("fruits_text.txt", 'w') as totxt_file:
totxt_file.write("\n".join(fruits))
请注意,这不会在最后一行的末尾插入行分隔符(此处为\n
),这在某些情况下可能会出现问题。
输出:
# cat fruits_text.txt
bananas
apples
oranges
strawberry
您可以将列表解压缩为 print
函数的参数,该函数支持文件输出的 file
关键字参数。使用 sep
关键字参数以换行符分隔每条记录:
with open("fruits_text.txt", 'w') as totxt_file:
print(*fruits, sep='\n', file=totxt_file)
您可以使用带有理解力的 writelines() 为每个字符串添加行尾:
fruits = ['bananas', 'apples', 'oranges', 'strawberry']
with open("fruits_text.txt", 'w') as totxt_file:
totxt_file.writelines(f+"\n" for f in fruits)