使用Python将CSV转换为txt,每10个值换行一次
我有一个CSV文件,里面有324行和495列的值。每一行和每一列的值都是一样的。
我需要把这个数组拆分,每10个值放到新的一行里。所以对于每一行,会有49列是完整的10个值,还有1列是5个值(495列 ÷ 10个值 = 49行完整的10个值和1行5个值)。然后再处理下一行,依此类推,总共处理324行。
我遇到的问题如下:
- line.split(",") 似乎没有任何作用。
- 在line.split之后的所有内容也似乎没有任何效果。
- 我不确定我的 for newrow in range... 是否正确。
- 我还没有把输出写入文本文件,我觉得应该是 outFile.write(这里放点什么,但我不确定是什么)。
- 我在打印语句后加了 "\n",但它只是把内容打印出来了。
我还是个初学者。
脚本:
import string
import sys
# open csv file...in read mode
inFile= open("CSVFile", 'r')
outFile= open("TextFile.txt", 'w')
for line in inFile:
elmCellSize = line.split(",")
for newrow in range(0, len(elmCellSize)):
if (newrow/10) == int(newrow/10):
print elmCellSize[0:10]
outFile.close()
inFile.close()
2 个回答
好的,这段脚本差不多能用,我觉得。
现在的问题是,它在写出第49行后就停止了。它为49行生成了10列数据,但实际上应该有第50行,只有5列数据,因为每行来自CSV文件的数据有495列。所以现在的脚本把最后10个值写成了49行,但没有处理那额外的5个值。而且,它还需要再处理323次,因为原始的CSV文件有324行。
所以,我觉得问题可能出在最后的if语句上,可能需要一个else语句,但我的elif语句没有起作用。我想让它检查列表中的第6个值是否是换行符('\n'),如果是的话,就把换行前的5个值写出来……但这没有成功。
感谢你们到目前为止的帮助,我很感激!
这是脚本:
import string
#import sys
#import csv
# open csv file...in read mode
inFile= open("CSVFile.csv", 'r')
outFile= open("TextFile.txt", 'w')
for line in inFile:
lineList = line.split(',') # Really, you should use csv reader
# Open the file to write to
with open('outFile', 'w') as outFile:
# iterate through the line
for index, value in enumerate(lineList):
if index % 10 == 0 and index != 0:
# Write the last 10 values to the file, separated by space
outFile.write('\t'.join(lineList[index-10:index]))
# new line
outFile.write('\n')
# print
print lineList[index-10:index]
elif lineList[6] == '\n':
# Write the last 5 values to the file, separated by space
outFile.write(' '.join(lineList[index-5:index]))
# new line
outFile.write('\n')
# print
print lineList[index-:index]
outFile.close()
inFile.close()
你其实应该使用csv模块,不过我还是可以给你一些建议。
你遇到的一个问题是,当你写 print elmCellSize[0:10]
的时候,你总是取前10个元素,而不是最近的10个元素。根据你想要的效果,你可以保存一个字符串来记住最近的10个元素。下面我会给你一个例子,同时提到一些你可以改进的地方。
首先要注意的是,line.split(',')
会返回一个列表。所以你用的变量名 elmCellSize
有点误导。如果你改成 lineList = line.split(',')
可能会更合适?或者你可以用 lineSize = len(line.split(','))
来表示这个列表的长度。
另外(虽然我对Python 2.x不太了解),我觉得 xrange
是Python 2.x中的一个函数,它比 range
更高效,但用法是一样的。
你可以用 if index % 10 == 0
来代替 if (newrow/10) == int(newrow/10)
,这样可以检查index是否是10的倍数。%
可以理解为“余数”,所以它会给出 newrow
除以 10
的余数。(比如:5 % 10 = 5;17 % 10 = 7;30 % 10 = 0)
现在,不要再用 [0:10]
来打印,这样总是打印前10个元素。你想要的是从当前索引向后打印10个元素。所以你可以用 print lineList[index-10:index]
来打印最近的10个元素。
最后你会得到类似这样的代码:
...
lineList = line.split(',') # Really, you should use csv reader
# Open the file to write to
with open('yourfile.ext', 'w') as f:
# iterate through the line
for index, value in enumerate(lineList):
if index % 10 == 0 and index != 0:
# Write the last 10 values to the file, separated by commas
f.write(','.join(lineList[index-10:index]))
# new line
f.write('\n')
# print
print lineList[index-10:index]
我并不是专家,但希望这些建议能帮到你!