You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决NavigableString写入文件时的TypeError错误?

解决TypeError: descriptor 'write' requires a 'file' object but received a 'NavigableString'问题

嘿,我一眼就揪出问题所在了!你打开文件时把文件实例存在了file_object变量里,但循环写入的时候却用了file.write(all)——这里的file是Python内置的文件类,不是你实际打开的那个文件对象,所以才会抛出这个错误。

快速修复代码

先修正变量名的问题,同时为了让内容换行显示,记得给每个写入的内容加个换行符,另外显式把NavigableString转成字符串更稳妥:

file_object = open("name-list.txt", "w") #Opening the file
name = soup.find(class_='table-responsive') #Extracting the data
name_list = name.find_all('td') #Refining the data
for final in name_list:
    content = final.contents[0] #Final result
    # 修正变量名+转字符串+加换行
    file_object.write(str(content) + '\n') 
file_object.close()

更优雅的写法(推荐)

用with语句可以自动帮你管理文件的打开和关闭,不用手动调用close(),避免忘记关闭文件的问题:

with open("name-list.txt", "w") as file_object:
    name = soup.find(class_='table-responsive')
    name_list = name.find_all('td')
    for final in name_list:
        content = final.contents[0]
        file_object.write(str(content) + '\n')

顺便解决你之前的CSV需求

你提到之前用csv库没法逐行添加,其实可以直接把表格数据写入CSV,比先写TXT再提取高效多了。假设你的表格是标准的行结构(tr为行,td为列),可以这样写:

import csv

with open("data.csv", "w", newline='') as csv_file:
    writer = csv.writer(csv_file)
    # 获取表格的所有行
    table_rows = soup.find(class_='table-responsive').find_all('tr')
    for row in table_rows:
        # 提取当前行的所有单元格内容,转成字符串列表
        row_content = [str(td.contents[0]) for td in row.find_all('td')]
        writer.writerow(row_content)

这样生成的CSV文件直接就能用表格软件打开,不用再额外处理TXT啦!

内容的提问来源于stack exchange,提问作者Ishaan Pathak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:17:41