我已经四处查看了一些教程,但仍然无法通过任何方式对此文件进行排序,因为它的排序非常奇怪!
文件如下:(其中x是数字,y是日期,z是时间,b是数字)
x x x x x
y y y y y
z z z z z
b b b b b
每行实际上有50个条目,但这是该文件的极简化版本。
我努力做的是对每个条目进行排序,以便它[x,y,z,b]
到目前为止,我所提出的就是将每一行分成一个列表,但这显然不是我需要做的事情,因此我被卡住了。
import csv
with open('sample.txt') as csvfile:
readCSV = csv.reader(csvfile, delimiter=' ')
for row in readCSV:
print(row)
答案 0 :(得分:2)
Numpy的转移就是你要找的,即
from csv import reader
from numpy import transpose
file = open("file.dat")
results = reader(file, delimiter=' ')
print(transpose(list(results)))
答案 1 :(得分:0)
这将打开您拥有原始值的test.txt文件,逐行执行并构造转置的数组数组。然后它迭代这些并按照你要求的顺序将它们打印到newText.txt以及csv。不确定你想要更多:)。
import csv
newLine = []
newArr = []
x = 0
with open ('text.txt', 'r') as f:
end = len(f.readline().replace(' ',''))
f.seek(0)
while x <= end:
for line in f:
newLine.append(line.split(" ")[x])
newArr.append(newLine)
x += 1
# outputs a text file
with open ('newText.txt', 'wb') as newf:
for line in newArr:
newf.write(' '.join(line) + '\n')
# outputs a csv file
with open('text.csv', 'wb') as csvfile:
writeCSV = csv.writer(csvfile)
for line in newArr:
writeCSV.writerow(''.join(line))
答案 2 :(得分:0)
排序文件:
x1 x2 x3 x4 x5
y y y y y
z z z z z
b b b b b
<强>程序:强>
import csv
with open("C:\\Users\\sortfile.csv", 'r') as fopen:
rows = csv.reader(fopen)
csvf = list(rows)
x = 0
array = []
while True:
lines = []
try:
for i in csvf:
lines.append(i[x])
array.append(lines)
x +=1
except IndexError:
break
<强>结果:强>
[['x1', 'y', 'z', 'b'], ['x2', 'y', 'z', 'b'], ['x3', 'y', 'z', 'b'], ['x4', 'y', 'z', 'b'], ['x5', 'y', 'z', 'b']]
我希望我能正确理解你的问题。
答案 3 :(得分:0)
假设:
$ cat so.csv
x1,x2,x3,x4,x5
y1,y2,y3,y4,y5
z1,z2,z3,z4,z5
b1,b2,b3,b4,b5
您通常会逐行读取文件:
import csv
LoL=[]
with open(fn) as f:
for row in csv.reader(f):
LoL.append(row)
或者,更紧凑:
LoT=[row for row in csv.reader(f)]
>>> LoL
[['x1', 'x2', 'x3', 'x4', 'x5'], ['y1', 'y2', 'y3', 'y4', 'y5'], ['z1', 'z2', 'z3', 'z4', 'z5'], ['b1', 'b2', 'b3', 'b4', 'b5']]
您可以使用zip
转换它:
with open(fn) as f:
LoT=[row for row in zip(*csv.reader(f))]
>>> LoT
[('x1', 'y1', 'z1', 'b1'), ('x2', 'y2', 'z2', 'b2'), ('x3', 'y3', 'z3', 'b3'), ('x4', 'y4', 'z4', 'b4'), ('x5', 'y5', 'z5', 'b5')]
然后,您可以根据需要将转置的元组列表写入新的csv或进程。