我在csv文件中有以下格式的数据
1)行人; - ; - ; - ; - ; 5.74; 0.018771; 2080.04; 522.40; 0.0000; 0.0000; 0.0000; 0.0000; 2080.04; 522.40; 0.0000; 0.0000; 0.0000; 41.7083; 2080.04; 522.40; 0.0000; 0.0000; 0.0000; 83.4167
2080.04; 522.40; 0.0000; 0.0000; 0.0000; 125.1250; 2080.04; 522.40; 0.0000; 0.0000; 0.0000; 166.8333;
2)行人; - ; - ; - ; - ; 5.74; 0.018771; 2104.25; 528.51; 0.0671; -0.3212; -0.1091; 178595.0833; 2104.30;
528.53; 0.0566; -0.3056; -0.1113; 178636.7917; 2104.34; 528.56; 0.0466; -0.2926; -0.1125; 178678.5000; 2104.39; 528.58; 0.0375; -0.2613; -0.1128; 178720.2083; 2104.44; 528.61; 0.0299; -0.2221; -0.1116;
78761.9167; 2104.48; 528.63; 0.0235; -0.0841; -0.1063; 178803.625;
此csv文件没有标题,并且每行没有相同的顺序。例如,某些行以分号(;)结尾,但有些行以数字结尾,而某些行以分号开头。我想改变这样的格式:
1; Pedestrian; - ; - ; - ; - ; 5.74; 0.018771; ----------------------------------------------
2; Pedestrian; - ; - ; - ; - ; 5.74; 0.018771;-----------------------------------------------
有没有优雅的解决方案?
答案 0 :(得分:0)
这可能会有所帮助。您可以使用csv module
来阅读您的文件。
<强>实施例强>
import csv
s = "PATH_TO.csv"
res = []
with open(s, 'r') as csvfile:
reader = csv.reader(csvfile, delimiter=';')
for line in reader:
if line:
if ")" in line[0]:
print "; ".join(line[:7]), "-"*46
<强>输出:强>
1) Pedestrian; - ; - ; - ; - ; 5.74; 0.018771; ----------------------------------------------
2) Pedestrian; - ; - ; - ; - ; 5.74; 0.018771; ----------------------------------------------