【问题标题】:Printing last lines of CSV file打印 CSV 文件的最后几行
【发布时间】:2018-07-05 21:23:22
【问题描述】:

我想打印保存为updated_quotes 的csv 文件的最后13 行。它返回一个语法错误。我怎样才能解决这个问题?

  import csv
from collections import deque

with open('updated_quotes', 'r') as csv_file:
    csv_reader = csv.reader(csv_file)


def tail(csv_file, n=13):
    'Return the last n lines of a file'
    print(return deque(open(csv_file), n))

【问题讨论】:

  • "语法错误";具体在哪里?

标签: python csv stocks


【解决方案1】:

您应该在tail 函数中打开文件并将文件对象传递给csv.reader

import csv
from collections import deque

def tail(csv_file, n=13):
    'Return the last n lines of a file'
     with open(csv_file, 'r') as f:
         csv_reader = csv.reader(f)
         return deque(csv_reader, n) 

print (tail("updated_quotes", n=13))

【讨论】:

    【解决方案2】:

    您的直接问题是tail 中的最后一行是:

    print(return deque(open(csv_file), n))
    

    我敢打赌,您在开发时拥有 print(deque(open(csv_file), n)),并打算将其编辑为 return(deque(open(csv_file), n))

    但这里还有更多错误。 tail 方法永远不会被调用。随着您的深入,我想您会发现使用 csv 阅读器的所有内容都需要放在 with 语句中。

    先试试这个:

    import csv
    from collections import deque
    
    def tail(csv_file_name, n=13):
        'Return the last n lines of a file'
        with open(csv_file_name, 'r') as csv_file:
            csv_reader = csv.reader(csv_file)
            return(deque(csv_reader, n))
    
    last_13 = tail('updated_quotes')
    print(last_13)
    

    【讨论】:

    • 这行得通,但会写入格式奇怪的 csv。我认为这是因为行是用双端队列而不是字符串编写的。是对的吗?非常感谢你的帮助。我刚开始学习编码,有点卡住了。
    • 对。看了之后,根本不是CSV,是deque(双端队列) 换句话说,文件是csv格式的文件。 Python csv 模块的全部意义在于将其一个 csv 转换为一系列数据行。通常这是一个列表,但如果你需要的话,它可以是一个双端队列。但是,如果您不需要双端队列,并且只需要 csv 文件的最后 13 行,请考虑使用 csv 将其读入列表,然后切出最后 13 行,然后使用 csv 将其写回.作家。
    猜你喜欢
    • 1970-01-01
    • 2015-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 2016-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多