使用python在csv文件头后插入多个常量值



是否可以在从第二行开始的CSV中插入9行新的常量值("AA") ?我需要插入"AA"在前9行(页眉之后)

原始CSV格式如下:

LEID,MI_RL,TOTDEPTH, INSERTED
07JW01,51,120,2/10/2014 10:37
DD18006,40,10,20/10/2018 16:55

最终的CSV应该是这样的:

LEID,MI_RL,TOTDEPTH, INSERTED
AA,AA,AA,AA
AA,AA,AA,AA
AA,AA,AA,AA
AA,AA,AA,AA
AA,AA,AA,AA
AA,AA,AA,AA
AA,AA,AA,AA
AA,AA,AA,AA
AA,AA,AA,AA
07JW01,51,120,2/10/2014 10:37
DD18006,40,10,20/10/2018 16:55

问题1

如何从第二列插入数据,"AA"从第2行到第9行,并自动将所有其他数据发送到一行?同时,我希望代码是动态的因为我只想告诉起始索引和结束索引它在这两个索引之间添加常数值?

问题2

另一个问题是,每个CSV有不同数量的列?查看另一个CSV文件有5列。

OLEID,FROM,TO,ZON,PROS
07WJ05,0,125,ARCN,ABC
DDH006,891.68,7854,BASE,DEF
DD1,25687,15987,GOOD,NEM

我代码:

import os

def prepend_multiple_lines(file_name, list_of_lines):
# define name of temporary dummy file
dummy_file = file_name + '.csv'
# open given original file in read mode and dummy file in write mode
with open(file_name, 'r') as read_obj, open(dummy_file, 'w') as write_obj:
# Iterate over the given list of strings and write them to dummy file as lines
for line in list_of_lines:
write_obj.write(line + 'n')
# Read lines from original file one by one and append them to the dummy file
for line in read_obj:
write_obj.write(line)
# remove original file
os.remove(file_name)
# Rename dummy file as the original file
os.rename(dummy_file, file_name)

def main():
print('*** Insert multiple lines from the second position of a file ***')
list_of_lines = ['AA','AA','AA','AA','AA','AA','AA','AA','AA'] #add 9 AA constant value
prepend_multiple_lines("DB_1.csv", list_of_lines)

if __name__ == '__main__':
main()

这段代码的问题是,它只向第一列添加了一个常量值,而忽略了所有其他列。此外,它还添加了before header。

我也尝试了插入方式,但它没有工作:

with open(r"db_1.csv", "r") as f:
contents = f.readlines()
contents.insert(2, 'AAA')
with open(r"db_1.csv", "w") as f:
contents = "".join(contents)
f.write(contents)   

CSV文件附件

帮忙吗? ?

使用csv模块,否则您将有很多问题解析它,包括多行和其他:

import csv
import itertools
import os
def add_placeholder_to_csv(csv_reader, csv_writer,
cell_placeholder, start_row, end_row):
# end_row is inclusive
headers = next(csv_reader)
cells_per_row = len(headers)
csv_writer.writerow(headers)
# Write everything until placeholder (-1 for header)
csv_writer.writerows(itertools.islice(csv_reader, start_row-1))

# Add placeholder
csv_writer.writerows(
[[cell_placeholder] * cells_per_row] * (end_row - start_row + 1))
# Write everything after placeholder
csv_writer.writerows(csv_reader)

with (open("mycsv.csv", newline="") as inputfile,
open("output.csv", "w", newline="") as outputfile):
reader = csv.reader(inputfile)
writer = csv.writer(outputfile)
add_placeholder_to_csv(reader, writer, "AA", 1, 7)
os.remove("mycsv.csv")
os.rename("output.csv", "mycsv.csv")

相关内容

  • 没有找到相关文章

最新更新