简体   繁体   English

使用 python 在 CSV 文件中的现有行之间插入一行

[英]Insert a line between existing lines in a CSV file using python

I am creating a script that writes lines to a CSV file using Python.我正在创建一个脚本,该脚本使用 Python 将行写入 CSV 文件。

For now, my script writes the CSV in this format:现在,我的脚本以这种格式编写 CSV:

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?你有什么想法?

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.我认为您可以尝试使用 Header Titles 获取行的索引,然后使用 append 添加新行,然后再次组合两个数据帧。 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.这将在 dataframe 之后返回。

   Title Row
0    Tom  20
1   nick  21
2  krish  19
3   jack  18
4  Rahib  25
5  Harry  21
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'})

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.感谢@harshal 的回答@Rahib 的回答,但我已经尝试 pandas 很长时间了,似乎无法让它工作,看起来它不太适合我的 CSV 格式。

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:最后,我查看了@Serge Ballesta 提供的帖子,实际上,一个简单的readlines和行索引的检索是一个非常简单的技巧:

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) output是文件名(传入参数), value是值列表(以“;”作为分隔符加入字符串), lookupi正在寻找的字符串(标题行)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 python 将行插入 csv 文件 - How to insert lines into csv file with python Python 模块 CSV 在 CSV 文件中的写入行之间添加一个空行 - Python Module CSV adds a blank line between writen lines in a CSV file 如何在python的文本文件中插入另一行之前的特定行,而不在任何行之间插入任何空行? - how to insert an specific line before another line, into a text file with python and without inserting any empty lines between any lines? 在 python 中的文件行之间插入文本 - Insert text in between file lines in python 如何使用python向现有文件添加行 - how to add lines to existing file using python 使用 python 将 csv 文件转换为 txt 文件时,不同行上的行间距不同 - Different level of spacing between rows on different lines while converting a csv file to txt file using python Python从文件中删除行/行,而无需修改现有内容 - Python delete line/lines from file without modifying existing contents 使用 Python 将文本文件插入现有的 xlsx - insert text file into existing xlsx using Python 读取csv行并将其另存为单独的txt文件,命名为行-python - Read csv lines and save it as seperate txt file, named as a line - python 如何在 Python 中将单行 csv 文件拆分为多行 - How to split single line csv file into multiple lines in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM