0

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)?

lena
  • 730
  • 2
  • 11
  • 23
  • 1
    Hint: open the file (as you would open any other plain text file: a csv file **is** a text file), open the .txt file in `"w"` mode, and loop 50 times reading a line from first file and writing it to second one... – Serge Ballesta Apr 01 '20 at 12:37
  • You want to create new multiple csv files from the old one file? Where do you need pandas? – Teshan Shanuka J Apr 01 '20 at 12:37
  • 1
    If you want to split the dataframe, you have the answer [here](https://stackoverflow.com/questions/17315737/split-a-large-pandas-dataframe) – Teshan Shanuka J Apr 01 '20 at 12:39
  • @TeshanShanukaJ, I have csv file having 200 row the data something like this(66.44 77.3 56,3 56,9 ...), now I want to read 50 line (50 values) form csv file and put these number in txt file , the final result must be 4 txt file each file have 50 number by using function – lena Apr 01 '20 at 12:43
  • Then @SergeBallesta has already said how you can do it – Teshan Shanuka J Apr 01 '20 at 12:52
  • OK, I will try now – lena Apr 01 '20 at 13:09
  • Can you see my update please? – lena Apr 01 '20 at 13:23

1 Answers1

0

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.

Sheldon
  • 4,084
  • 3
  • 20
  • 41