【问题标题】:Wrong output with a csv filecsv 文件的错误输出
【发布时间】:2022-01-21 11:15:16
【问题描述】:

程序的重点是获取一个包含一行或包含给定范围内的行的表格(通过行号)。该函数要么复制原始数据,要么创建一个与原始数据集 (copy_table = False) 一起使用的新表视图,因此通过此视图所做的更改也将在原始表中观察到。 这是我的代码:

import csv

def get_rows_by_number(file, start, stop, copy_table=False):
    if start >= stop:
        print('Wrong range')
    res = []
    csv.field_size_limit(1000000000)
    try:
        with open(file, mode='r') as f:
            read = csv.reader(f, delimiter=';')
            for i in read:
                res.append(i)
    except IOError:
        print('This file does not exist')
    if copy_table:
        with open(file, mode='w', newline='') as f:
            write = csv.writer(f, delimiter=';', lineterminator='\r')
            for i in range(start, stop):
                print(res)
                write.writerow(res)
    else:
        with open(file, mode='w', newline='') as f:
            write = csv.writer(f, delimiter=';', lineterminator='\r')
            for i in range(start, stop):
                print(res)
                write.writerow(res)

get_rows_by_number(r'participants.csv', 1, 4, False)

我猜这里出了点问题,因为输出只是整个表,而不是给定范围内的行。 如果需要,链接到 participants.csv 文件。

【问题讨论】:

标签: python csv


【解决方案1】:

我想你应该使用

write.writerow(res[i])

改为

write.writerow(res)

【讨论】:

  • 现在它显示文件“C:\Users\Nika\PycharmProjects\pythonProject5\main.py”,第 32 行,在 get_rows_by_number(r'C:\Users\Nika\PycharmProjects\pythonProject5 \participants.csv', 1, 4, False) 文件“C:\Users\Nika\PycharmProjects\pythonProject5\main.py”,第 30 行,在 get_rows_by_number 中 print(res[i]) IndexError: list index out of range : /
  • 测试了我的解决方案,它对我有用。您确定您的文件包含的行数超过了 stop 参数的值吗?
猜你喜欢
  • 2018-07-07
  • 2019-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多