[英]How to split values in a list by string and not by characters?
I have read in a text file and split the rows up into two separate lists. 我已经阅读了一个文本文件,并将行分成两个单独的列表。 I'm trying to convert each of these two lists into a csv but I am running into a bit of a problem. 我正在尝试将这两个列表中的每一个都转换为csv,但是我遇到了一个问题。
My current python code (using python 3) to do the writing to csv looks like this: 我当前使用python 3编写的python代码(如下所示):
with open(bad_csv_file, 'w') as myfile:
wr = csv.writer(myfile)
for item in bad_csv:
wr.writerow(item)
myfile.close()
The rows I'm trying to write to csv look like this: 我要写入csv的行如下所示:
0000002 1 1E-10 1851 7 5 12 1851
0000002 0 -97.6 22.2 -9999 -9999 0 0 97687 101325 45728 41.2 1e+05 1 0 0 0 0 0 -9999 -9999 -9999 -9999
0000003 1 1E-10 1851 7 10 12 1851
0000003 0 -60 12 -9999 -9999 0 0 99993 101325 55402 25.7 1e+05 1 0 0 0 0 0 -9999 -9999 -9999 -9999
0000004 50 1E-10 1851 8 16 0 1851
My current output looks like: 我当前的输出如下所示:
2,0,1,0,1,0,0,2, ,1,5,8, ,1, ,1,5,8, ,1,4,1,6, ,0, ,0, ,0, ,0, ,0, ,0, ,0, ,0, ,0, ,0, ,0, ,0, ,0, ,0, ,0, , , ,"
"
0,0,0,0,0,0,1, ,1,4, ,1,E,-,1,0, ,1,8,5,1, ,6, ,2,5, ,0, ,1,8,5,1, , , , , , , , , , , , , , , ,"
"
0,0,0,0,0,0,2, ,1, ,1,E,-,1,0, ,1,8,5,1, ,7, ,5, ,1,2, ,1,8,5,1, , , , , , , , , , , , , , , ,"
"
0,0,0,0,0,0,2, ,0, ,-,9,7,.,6, ,2,2,.,2, ,-,9,9,9,9, ,-,9,9,9,9, ,0, ,0, ,9,7,6,8,7, ,1,0,1,3,2,5, ,4,5,7,2,8, ,4,1,.,2, ,1,e,+,0,5, ,1, ,0, ,0, ,0, ,0, ,0, ,-,9,9,9,9, ,-,9,9,9,9, ,-,9,9,9,9, ,-,9,9,9,9,"
"
0,0,0,0,0,0,3, ,1, ,1,E,-,1,0, ,1,8,5,1, ,7, ,1,0, ,1,2, ,1,8,5,1, , , , , , , , , , , , , , , ,"
It seems to be splitting by character as opposed to the entire string of the number. 它似乎是按字符分割的,而不是数字的整个字符串。 Any help would be greatly appreciated, thanks! 任何帮助将不胜感激,谢谢!
Firstly, in your code you iterate over bad_csv
which is unbound as far as the reader knows. 首先,在您的代码中,您遍历bad_csv
,据读者所知, bad_csv
是未绑定的。 The naming could be somewhat more clear to make us understand what you mean to do. 为了使我们理解您的意思,命名可能会更清楚。
Secondly, if you iterate over a string
it'll do it char
by char
. 其次,如果我们通过遍历string
它会做到这一点char
的char
。 A row
in the csvwriter
is a sequence of strings or numbers . 一row
在csvwriter
是序列字符串或数字 。 It'll iterate over that. 它将遍历。 What you need to do is to split your string
on spaces
. 您需要做的是将string
拆分为spaces
。 row = line.split(' ')
Then row
will be a sequence of your values. row = line.split(' ')
然后row
将是您的值序列。 If you want to remove the spaces in the end use row = line.rstrip().split(' ')
如果要删除最后的空格,请使用row = line.rstrip().split(' ')
Oh and you don't need to close a file if you opened it with with
. 哦,如果你打开了它,你不必关闭文件with
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.