在python中以字符串而不是字节的形式打开文件

2024-05-29 04:25:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个项目,它读取一个包含ICS文件(icalendar)的url。与其把它读成字符串,不如把它打印成字节,我们需要一些建议。你知道吗

import requests
url = "http://ical.keele.ac.uk/index.php/ical/ical/15021113"
c = requests.get(url)
c.encoding = 'ISO-8859-1'
print(c.content)

预期收益

BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//hacksw/handcal//NONSGML v1.0//EN
BEGIN:VEVENT

实际收益

b"BEGIN:VCALENDAR\rVERSION:2.0\rPRODID:-//hacksw/handcal//NONSGML v1.0//EN\rBEGIN:VEVENT\r

我曾尝试直接使用ics文件,没有任何问题,但当我从url请求它不工作。谢谢


Tags: 文件项目url收益requestsenicalendarics
1条回答
网友
1楼 · 发布于 2024-05-29 04:25:03

神志不清的莴苣是对的,只要用文字:

http://docs.python-requests.org/en/master/user/quickstart/#response-content

import requests
url = "http://ical.keele.ac.uk/index.php/ical/ical/15021113"
c = requests.get(url)
#c.encoding = 'ISO-8859-1'
#print(c.content)
print(c.text[:10])

结果

BEGIN:VCAL

(3.6.1 32位窗口)

相关问题 更多 >

    热门问题