在 python 中将文件作为字符串而不是字节打开
Open file as string instead of bytes in python
我正在开发一个读取 url 的项目,其中包含一个 ICS 文件 (icalendar)。与其将其作为字符串读取,不如将其作为字节打印,需要对此提出一些建议。
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)
预计return
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//hacksw/handcal//NONSGML v1.0//EN
BEGIN:VEVENT
实际return
b"BEGIN:VCALENDAR\rVERSION:2.0\rPRODID:-//hacksw/handcal//NONSGML v1.0//EN\rBEGIN:VEVENT\r
我试过直接使用 ics 文件并且没有任何问题,但是当我从 url 请求时它不起作用。谢谢
Delirious Lettuce 说的对,就用文字:
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 位 windows)
我正在开发一个读取 url 的项目,其中包含一个 ICS 文件 (icalendar)。与其将其作为字符串读取,不如将其作为字节打印,需要对此提出一些建议。
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)
预计return
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//hacksw/handcal//NONSGML v1.0//EN
BEGIN:VEVENT
实际return
b"BEGIN:VCALENDAR\rVERSION:2.0\rPRODID:-//hacksw/handcal//NONSGML v1.0//EN\rBEGIN:VEVENT\r
我试过直接使用 ics 文件并且没有任何问题,但是当我从 url 请求时它不起作用。谢谢
Delirious Lettuce 说的对,就用文字:
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 位 windows)