0

I am creating a script that writes lines to a CSV file using Python.

For now, my script writes the CSV in this format:

Title row 
Value1;Value2;.... (more than 70)
Title row2 
Value1;Value2;...

I just want to be able to read the file again and insert a line of values in between rows, like the following:

Title row 
Value1;Value2;.... (more than 70)
Value1;Value2;....
Title row2 
Value1;Value2;...

Do you have any ideas?

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Searme
  • 26
  • 1
  • 7
  • Any reference code (your attempt) on which base an answer? – Roberto Caboni Feb 12 '21 at 08:54
  • Not voting to close as a duplicate, but a CSV file is a text file. So [this question](https://stackoverflow.com/q/10507230/3545273) is relevant, and IMHO [this answer](https://stackoverflow.com/a/62366144/3545273) is specialy interesting – Serge Ballesta Feb 12 '21 at 09:30
  • Thanks, I provided my solution in the answers thanks to the post you linked! – Searme Feb 12 '21 at 10:28
  • Welcome to Stack Overflow! No answers in the question, please. I have rolled back/edited your question and removed the answer. Add the answer in the answer section only. – Sabito stands with Ukraine Feb 12 '21 at 10:29

3 Answers3

0

I think you can try getting the index of the row with Header Titles and then use append to add new rows and then again combine the two dataframes. Here is the code that might work for you.

import pandas as pd 

# intialise data of lists. 
data = {'Title':['Tom', 'nick', 'krish', 'jack','Title','Harry'], 
        'Row':[20, 21, 19, 18,'Row',21]}
new_data = {'Title':['Rahib'], 
        'Row':[25]}     
  
# Create DataFrame 
df = pd.DataFrame(data) 
new_df = pd.DataFrame(new_data)
#print(df)

index = df[df['Title'] == 'Title'].index.values.astype(int)[0]

upper_df = df.loc[:index-1]
lower_df = df.loc[index+1:]

upper_df = upper_df.append(new_df)
upper_df = upper_df.append(lower_df).reset_index(drop=True)

print(upper_df)

This will return following dataframe.

   Title Row
0    Tom  20
1   nick  21
2  krish  19
3   jack  18
4  Rahib  25
5  Harry  21
Dharman
  • 30,962
  • 25
  • 85
  • 135
Rahib
  • 462
  • 3
  • 10
0
import csv

with open('csvfile.csv', mode='w') as csv_file:
    fieldnames = ['Title', 'row']
    writer = csv.DictWriter(csv_file, delimiter=';',fieldnames=fieldnames)
    writer.writeheader()
    writer.writerow({'Title': 'Value1', 'row': 'Value2'})
0

Thanks to @harshal's answer and @Rahib's answer, but I've already tried pandas for a long time, and can't seem to get it to work, looks like it's not really suited for my CSV format.

Finally, I've looked at the posts provided by @Serge Ballesta, and in fact, a simple readlines and the retrieval of the line index is a pretty simple trick:

with open(output) as myFile:
    for num, line in enumerate(myFile, 1):
        if lookup in line:
            index = num

f = open(output, "r")
contents = f.readlines()

value=';'.join(value)
f.close()
contents.insert(index+1, str(value)+'\n')

f = open(output, "w")
contents = "".join(contents)
f.write(contents)
f.close()

With output being the name of the file (passed in parameters), value being a list of values (joined for a string with ";" as delimiter), and lookup being the string i was looking for (the title row)

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Searme
  • 26
  • 1
  • 7