首页 > 解决方案 > python csv拆分器不起作用

问题描述

我正在尝试制作一个 .csv 拆分器。我应该从原始 csv 文件中获取 x 行数并使用该行数制作新的 csv 文件。

import os
import csv

fileDir = ('C:\\somedir\\')
fName = input('Write the file name here, without extention:  ')
lineNo = int(input('Number of lines pr csv file:  '))
fNameF = (fName + '.csv')
filehandler = (fileDir + fNameF)

def split(filehandler, delimiter=',', row_limit=lineNo, 
    output_name_template='fName_%s.csv', output_path=fileDir, keep_headers=True):
    reader = csv.reader(filehandler, delimiter=delimiter)
    current_piece = 1
    current_out_path = os.path.join(
         output_name_template  % current_piece
    )
    current_out_writer = csv.writer(open(current_out_path, 'w'))
    current_limit = row_limit
    if keep_headers:
        headers = reader.next()
        current_out_writer.writerow(headers)
    for i, row in enumerate(reader):
        if i + 1 > current_limit:
            current_piece += 1
            current_limit = row_limit * current_piece
            current_out_path = os.path.join(
               output_name_template  % current_piece
            )
            current_out_writer = csv.writer(open(current_out_path, 'w'))
            if keep_headers:
                current_out_writer.writerow(headers)
        current_out_writer.writerow(row)

它运行脚本,但没有任何反应,有人可以帮助我吗?

标签: pythonpython-3.x

解决方案


我认为您根本没有调用该函数split()。而且您还将函数中的所有值作为参数传递。检查您是否使用以下代码获得输出。

import os
import csv

fileDir = ('C:\\somedir\\')
fName = input('Write the file name here, without extention:  ')
lineNo = int(input('Number of lines pr csv file:  '))
fNameF = (fName + '.csv')
filehandler = (fileDir + fNameF)

def split(filehandler, delimiter, row_limit, 
output_name_template, output_path, keep_headers):

    reader = csv.reader(filehandler, delimiter=delimiter)
    current_piece = 1
    current_out_path = os.path.join(
         output_name_template  % current_piece
    )
    current_out_writer = csv.writer(open(current_out_path, 'w'))
    current_limit = row_limit
    if keep_headers:
        headers = reader.next()
        current_out_writer.writerow(headers)
    for i, row in enumerate(reader):
        if i + 1 > current_limit:
            current_piece += 1
            current_limit = row_limit * current_piece
            current_out_path = os.path.join(
               output_name_template  % current_piece
            )
            current_out_writer = csv.writer(open(current_out_path, 'w'))
            if keep_headers:
                current_out_writer.writerow(headers)
        current_out_writer.writerow(row)
split(filehandler,',', lineNo,'fName_%s.csv', fileDir, True)

推荐阅读