将文件读取到列表,然后打印

2024-10-01 07:40:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图读取一个文本文件并将其数据附加到一个列表中,然后打印出来。 然而,我遇到了一些困难,因为当我打印列表时,它是空的,而我的代码显然附加了文本文件数据

我读过类似的问题,并试图复制它们的结果,但无济于事

你们谁能看出我做错了什么吗

以下是我的代码的重要片段:

def parse_feed(rss_url):
    ''' This function parses the Yahoo! RSS API for data of the latest five articles, and writes it to companyNews.txt'''

# Define the RSS feed to parse from, as the url passed in of the company the user chose
    feed = feedparser.parse(rss_url)

# Define the file to write the news data to, companyNews.txt
    outFile = open('companyNews.txt', mode='w')

# Create a list to store the news data parsed from the Yahoo! RSS
    news_data_write = []
# Initialise a count
    count = 0
# For the number of articles to append to the file, append the article's title, link, and published date to the news_elements list
    for i in range(2):
        news_data_write.append({feed['entries'][count].title,
                      feed['entries'][count].link,
                      feed['entries'][count].published})
# Add one to the count, so that the next article is parsed
        count+=1
# For each item in the news_elements list, convert it to a string and write it to companyNews.txt
        for item in news_data_write:
            item = str(item)
            outFile.write(item)
# For each article, write a new line to companyNews.txt, so that each article's data is on its own line
        outFile.write('\n')
        print(news_data_write)
# Clear the news_elements list so that data is not written to the file more than once
        del(news_data_write[:])

        read_news_file()

def read_news_file():


    with open('companyNews.txt', mode='r') as inFile:
        news_data = inFile.read()

    news_data_list = news_data.splitlines()

    print(news_data_list)

Tags: thetointxtdataparsefeedcount