Python中如何读取文本文件?在线求助

http://news.gtimg.cn/notice_more.php?q=sz300144&page=1
如何能用比较简便的方法直接读取 finance_notice ={…}这段话然后直接将其变成一个字典变量,并把其中的 ASCII 转换成文字。
Python中如何读取文本文件?在线求助

5 回复

s = requests.get(“http://news.gtimg.cn/notice_more.php?q=sz300144&page=1”)
t = s.text[20:-2]
t = t.replace("’", ‘"’)
json.loads(t)


# 读取文本文件最常用的几种方法:

# 方法1:一次性读取整个文件(适合小文件)
with open('example.txt', 'r', encoding='utf-8') as file:
    content = file.read()
    print(content)

# 方法2:逐行读取(适合大文件)
with open('example.txt', 'r', encoding='utf-8') as file:
    for line in file:
        print(line.strip())  # strip()去掉换行符

# 方法3:读取所有行到列表
with open('example.txt', 'r', encoding='utf-8') as file:
    lines = file.readlines()
    for line in lines:
        print(line.strip())

# 方法4:使用readline逐行读取
with open('example.txt', 'r', encoding='utf-8') as file:
    line = file.readline()
    while line:
        print(line.strip())
        line = file.readline()

# 关键参数说明:
# 'r' - 只读模式
# encoding='utf-8' - 指定编码,避免中文乱码
# with语句 - 自动管理文件关闭

# 如果要读取的文件不存在,可以这样处理:
try:
    with open('example.txt', 'r', encoding='utf-8') as file:
        content = file.read()
except FileNotFoundError:
    print("文件不存在")
except UnicodeDecodeError:
    print("编码错误,尝试其他编码如gbk")

# 简单总结:小文件用read(),大文件用逐行读取。

最常用的就是with open() as file:配合read()for line in file:,记得指定编码。

import requests

res = requests.get(“http://news.gtimg.cn/notice_more.php?q=sz300144&page=1”)

text = res.content.decode()
json_text = text[text.find("{"):text.rfind("}") + 1].replace("’", ‘"’)

import json

json.loads(json_text)

朋友能不能用 P3 写一下

谢谢,PY3 也可以安装 requests

回到顶部