python - 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)
它运行脚本,但没有任何反应,有人可以帮助我吗?
解决方案
我认为您根本没有调用该函数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)
推荐阅读
- python - AttributeError:“TwoCaptcha”对象没有属性“recaptcha”
- javascript - 我可以在不使用 Babel 的情况下在 ES6 中使用 Webpack 吗?
- reactjs - send Data from react to django rest api
- javascript - 如何使用纯 JavaScript 获取 DIV 元素的 id 和标题
- android - 如何为文本视图(文本大小)的共享元素转换进行自定义转换
- reactjs - 使用控件将视频播放器添加到 GLB 模型
- reactjs - 为什么使用无效数据调用此错误函数 Query.where()。不支持的字段值:firebase 中发生未定义?
- c++ - 我在 Visual Studio 中使用 C++ 的 openFrameworks 库设置项目时遇到问题
- python - 具有不同值但索引相同的熊猫子集
- java - 将此 if 语句与封闭语句合并