我有一个csv文件,其中包含以下行:
0.10089,0,0,1,0,0,0,0,0,0,-1.8,-0.7,1999998.0,0,0,0,80,81.226,158.25,0
0.10955,0,0,2,0,0,0,0,0,0,-1.5,0.4,-4.1,0,0,0,88.127,87.784,158.47,0
我想复制每一行3次,然后更改每行(1,2,...)
中的第4个元素,以便所有行(包括复制行)成为此顺序的一部分
0.10089,0,0,1,0,0,0,0,0,0,-1.8,-0.7,1999998.0,0,0,0,80,81.226,158.25,0
0.10089,0,0,2,0,0,0,0,0,0,-1.8,-0.7,1999998.0,0,0,0,80,81.226,158.25,0
0.10089,0,0,3,0,0,0,0,0,0,-1.8,-0.7,1999998.0,0,0,0,80,81.226,158.25,0
0.10955,0,0,4,0,0,0,0,0,0,-1.5,0.4,-4.1,0,0,0,88.127,87.784,158.47,0
0.10955,0,0,5,0,0,0,0,0,0,-1.5,0.4,-4.1,0,0,0,88.127,87.784,158.47,0
0.10955,0,0,6,0,0,0,0,0,0,-1.5,0.4,-4.1,0,0,0,88.127,87.784,158.47,0
我知道每个逗号的索引,因此知道第4个元素的位置
with fileinput.input(inplace=True) as f:
for line in f:
line = line.rstrip('\n')
comma_pos_array = [i for i,x in enumerate(line) if x == ',']
for i in range(3):
print(line)
我尝试过从0 to (number of lines in f)*3
创建一个连续整数数组然后用这个新数组中相应元素更改第4个元素的方法,但它们似乎不起作用。
任何帮助将不胜感激!
答案 0 :(得分:0)
这是使用csv
module读取和写入输入/输出的变体:
from io import StringIO
from csv import reader, writer
txt = '''0.10089,0,0,1,0,0,0,0,0,0,-1.8,-0.7,1999998.0,0,0,0,80,81.226,158.25,0
0.10955,0,0,2,0,0,0,0,0,0,-1.5,0.4,-4.1,0,0,0,88.127,87.784,158.47,0'''
REPEAT = 3
with StringIO(txt) as infile, StringIO() as outfile:
rows = reader(infile)
out_csv = writer(outfile)
counter = 0
for row in rows:
for i in range(REPEAT):
counter += 1
row[3] = counter
out_csv.writerow(row)
print(outfile.getvalue())
并生成输出:
0.10089,0,0,1,0,0,0,0,0,0,-1.8,-0.7,1999998.0,0,0,0,80,81.226,158.25,0
0.10089,0,0,2,0,0,0,0,0,0,-1.8,-0.7,1999998.0,0,0,0,80,81.226,158.25,0
0.10089,0,0,3,0,0,0,0,0,0,-1.8,-0.7,1999998.0,0,0,0,80,81.226,158.25,0
0.10955,0,0,4,0,0,0,0,0,0,-1.5,0.4,-4.1,0,0,0,88.127,87.784,158.47,0
0.10955,0,0,5,0,0,0,0,0,0,-1.5,0.4,-4.1,0,0,0,88.127,87.784,158.47,0
0.10955,0,0,6,0,0,0,0,0,0,-1.5,0.4,-4.1,0,0,0,88.127,87.784,158.47,0
(您需要将StringIO
部分替换为您的文件;我在这里使用它们来使示例自包含)
答案 1 :(得分:0)
这将产生你想要的(没有csv模块):
static_app
--admin
---css
---fonts
---img
---js
--static
---css
----nav_style.css
---fonts
---html
----myapp
-----base.html
---img
----stretchy_nav_cd-sprite-3.svg
---js
--...