将文件读入列表并打印

时间:2016-07-16 13:52:17

标签: python python-3.x

我正在尝试读取文本文件并将其数据附加到列表中,然后打印出来。 但是我遇到了困难,因为当我打印列表时,它是空的,当我的代码清楚地附加了文本文件数据时。

我已经阅读了类似的问题并试图复制他们的结果,但无济于事。

你们中间有人能看出我做错了吗?

以下是我的代码的重要摘要:

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)

0 个答案:

没有答案