Python:将变量结果打包为文本以将其附加到文本文件

Python: Pack variable result as text to append it to a text file

程序从网站获取标题列表。然后存储在一个变量(listOfjobs)中。我希望能够写入该变量的内容(职位列表)并将其附加到现有的文本文件,但它告诉我只接受字符串。如何将 listOfJobs 值的打印输出作为纯文本包含在文本文件中?谢谢!

from selenium import webdriver

browser = webdriver.Firefox()
browser.get('https://jobs.theguardian.com/searchjobs/?LocationId=1500&keywords=personal+assistant&radialtown=London+(Central)%2c+London+(Greater)&countrycode=GB')

elem = browser.find_elements_by_class_name('lister__header')

for el in elem:                 
   listOfJobs = print(el.text)
    print(listOfJobs)


import os
helloFile = open('C:\Users\sk\PycharmProjects\test\test_email.txt', 'w')
helloFile.write(websiteText)
helloFile.close()

作为字符串追加到文件列表:

'\n'.join(str(el) for el in listOfjobs)

最好使用上下文管理器进行文件处理:

with open('C:\Users\sk\PycharmProjects\test\test_email.txt', 'a') as res:
    res.write(''.join(str(el) for el in listOfjobs))

每次 运行 代码时,您需要使用 a 打开以附加,w 覆盖:

from selenium import webdriver

browser = webdriver.Firefox()
browser.get('https://jobs.theguardian.com/searchjobs/?LocationId=1500&keywords=personal+assistant&radialtown=London+(Central)%2c+London+(Greater)&countrycode=GB')

elem = browser.find_elements_by_class_name('lister__header')


with open('C:\Users\sk\PycharmProjects\test\test_email.txt', "a") as f:
    for el in elem:                 
       f.write(el.text+"\n")