Python每第n行输出一次,不带Panda



我是Python的新手,我的任务是用Python重写CSV。我已经为我的任务编写了一个工作脚本。现在我只想得到CSV的每10行作为输出。有简单的方法吗?我已经试着用Jason Reeks的答案了。现在它工作了,谢谢!

import csv
import sys
userInputFileName = sys.argv[1]
outPutFileSkipped = userInputFileName.split('.')[0] + '-Skipped.csv'
cnt = 0
first = True
with open(outPutFileSkipped, 'w', newline='') as outputCSV:
csv_reader_object_skipped = csv.reader((x.replace('', '') for x in open(userInputFileName)), delimiter=',')
csv_writer_object_skipped = csv.writer(outputCSV, delimiter=',')
for row, line in enumerate(csv_reader_object_skipped):
if row % 10 == 0:
print(line)
csv_writer_object_skipped.writerow(line)
print('Es wurden erfolgreich ' + str(cnt) + ' Zeilen formatiert!')

这里有一种没有熊猫的本地方法:

import csv
with open('file.csv', 'r') as f:
reader = csv.reader(f)
for row, line in enumerate(reader):
# Depending on your reference point you may want to + 1 to row 
# to get every 10th row.
if row % 10 == 0:  
print(line)

Pandas有一个简单的方法:

import pandas as pd
df = pd.DataFrame({"a": range(100), "b": range(100, 200)})
df.loc[::10]

相关内容

  • 没有找到相关文章

最新更新