如何将此列表保存到 Python 中的文本文件

How to save this list to a text file in Python

import urllib.request
import re
import json
import csv
x = 4
search_keyword = input("Enter the keyword ")
html = urllib.request.urlopen("https://www.youtube.com/results? 
search_query=" + search_keyword + "&sp=EgIIAQ%253D%253D")
video_ids = re.findall(r"watch\?v=(\S{11})", html.read().decode())
for i in video_ids:
    print("https://www.youtube.com/watch?v=" + i, end = ' ')

我是 Python 的新手,最近找到了如何在 Python 中查找 YouTube 链接的教程,我想将链接列表保存到文本文件中,但它给了我一个错误:

TypeError: 'NoneType' object is not iterable

您似乎想将视频链接写入文本文件,但我注意到您正在导入 csv 模块(从技术上讲,您在这里不需要它)

如果您的对象是 None,为避免类型错误,您可以显式构建视频链接列表:

video_urls = ['https://www.youtube.com/watch?v=' + i for i in video_ids or []]

注意 video_ids or [] 部分是为了防止 video_ids 对象本身是 None.

然后将其保存到输出文本文件:

with open('out1.txt', 'w') as out_file:
    out_file.write('\n'.join(video_urls))

with Python 3 使用 pathlib 模块,它变得更加容易(这只是包装上面相同逻辑的快捷方式):

from pathlib import Path

Path('out2.txt').write_text('\n'.join(video_urls))