[英]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
是值列表(以“;”作为分隔符加入字符串), lookup
是i
正在寻找的字符串(标题行)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.