繁体   English   中英

将\\ n写入.txt文件不会换行,只是说\\ n

[英]Writing \n to .txt file does not make a newline, just says \n

所以我有这段代码:

#! python3
import requests
import bs4
import time
import sys

messages = []

for i in range(3):
    # initiating request
    res = requests.get('https://supermariomakerbookmark.nintendo.net/')
    try:
        res.raise_for_status()
    except Exception as e:
        # handling error
        print('Error while requesting from bookmark:')
        print(e)
        time.sleep(3)
        sys.exit()

    # If gotten to this point, request has been succesfully made

    # creating soup element
    soup = bs4.BeautifulSoup(res.text, features='html.parser')

    # selecting elements
    elems = soup.select('div[class="course-title"]')
    if elems[0].getText() not in messages:
        print(elems[0].getText())
        messages.append(elems[0].getText())
    time.sleep(0.3)

with open('db.txt', 'w+') as f:
    data = '\n'.join(messages).encode('ascii', 'ignore')
    f.write(str(data))

您可能已经发现,我正在尝试在名为db.txt的文件中写出3个随机的Mario制造商级别(显然,我不会仅将其用于3个级别,可能是500/700,但这只是一个例)。 问题是,当我检查txt文件时,它将是这样的:

b"foo\nbar\nbaz"

但我想要这样:

b"""
foo

bar

baz
"""

有人能帮我吗?

更换

data = '\n'.join(messages).encode('ascii', 'ignore')

data = '\n'.join(messages)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM