简体   繁体   中英

Function to read specific lines from CSV file with pandas

I have a CSV file containing 200 lines. I want to create a function to read every 50 lines together and then store these (50 lines) in a .txt file until the csv file ends. How can I do that please? Any help appreciated.

import pandas as pd
import csv

def my_function(n):
  dataset = pd.read_csv('e.csv', nrows=50) 
  X = dataset.iloc[:,[0,0]].values

Update::

def my_function(n):

dataset = pd.read_csv('e.csv', nrows=n) 
X = dataset.iloc[:,[0,0]].values


with open('funct.txt', 'w') as file:
    for i in X:
        file.write("{}\n".format(i))

return

row_count = len(open("e.csv").readlines())
print(row_count)
n=50

my_function(n)

Now my problem how can read each 50 lines after another in each time until reach to the maximum length (200)?

You could test the remainder of the euclidean division of the index by 50 to check if your row number is a multiple of 50:

df=pd.read_csv('e.csv')
df=df[df.index%50==0]
df.to_csv('newfile.txt')

This way you do not need to iterate over your dataframe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM