我有500000个数值txt file.Couple of lines
-938.549927
-938.542419
-938.534912
-938.523621
-938.523621
-938.512329
-938.512329
-938.523621
-938.519836
-938.523621
-938.519836
-938.508606
-938.508606
-938.508606
-938.519836
-938.531128
-938.538635
我想将它保存为csv文件。我试过这个
import csv
lines = [line.rstrip('\n') for line in open('d500.txt')]
myfile = open('n500.csv', 'wb')
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerow(lines)
我得到了这个
wc -l n500.csv
1 n500.csv
只是文件的一部分
358337 "," -938.362061 "," -938.369568 "," -938.369568 "," -938.369568 "," -938.380859 "," -938.377075 "," -938.380859 "," -938.373352 "," -938.347046 "," -938.343262 "," -938.339539 "," -938.324524 "," -938.313232 "," -938.328247 "," -938.320740 "," -938.320740 "," -938.328247 "," -938.324524 "," -938.324524 "," -938.316956
我真正想要的是这样的事情
-938.316956
-938.316956
-938.313232
如果我尝试
wr.writerows(lines)
格式很疯狂
" "," ","-","9","3","8",".","3","1","3","2","3","2"," "," "," "," "
" "," ","-","9","3","8",".","3","2","8","2","4","7"," "," "," "," "
" "," ","-","9","3","8",".","3","2","0","7","4","0"," "," "," "," "
" "," ","-","9","3","8",".","3","2","0","7","4","0"," "," "," "," "
" "," ","-","9","3","8",".","3","2","8","2","4","7"," "," "," "," "
" "," ","-","9","3","8",".","3","2","4","5","2","4"," "," "," "," "
" "," ","-","9","3","8",".","3","2","4","5","2","4"," "," "," "," "
" "," ","-","9","3","8",".","3","1","6","9","5","6"," "," "," "," "
" "," ","-","9","3","8",".","3","1","3","2","3","2"," "," "," "," "
" "," ","-","9","3","8",".","3","1","3","2","3","2"," "," "," "," "
" "," ","-","9","3","8",".","3","0","9","4","4","8"," "," "," "," "
" "," ","-","9","3","8",".","3","1","6","9","5","6"," "," "," "," "
" "," ","-","9","3","8",".","3","1","6","9","5","6"," "," "," "," "
" "," ","-","9","3","8",".","3","1","3","2","3","2"," "," "," "," "
我的新代码版本
import csv
lines = [[line.rstrip('\n')] for line in open('d500.txt')]
myfile = open('n500.csv', 'wb')
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerows(lines)
比我得到
" -938.324524 "
" -938.313232 "
" -938.328247 "
" -938.320740 "
" -938.320740 "
" -938.328247 "
" -938.324524 "
" -938.324524 "
" -938.316956 "
" -938.313232 "
" -938.313232 "
" -938.309448 "
" -938.316956 "
" -938.316956 "
" -938.313232 "
如何摆脱引号?
答案 0 :(得分:2)
在循环中使用writeline
import csv
with open('n500.csv', 'wb') as myfile:
wr = csv.writer(myfile)
[wr.writerow(line.rstrip('\n')) for line in open('d500.txt')]
with
语句处理文件关闭。
答案 1 :(得分:2)
您所要做的就是将.txt重命名为.csv(或复制到.csv文件)。
由于只有一列,因此不需要( c omma) s 操作符。