繁体   English   中英

在没有 pandas 的情况下写入 CSV

[英]Writing to a CSV without pandas

我正在将数字列表写入 CSV。

但是,它将每个数字放入不同的单元格中。

我不明白为什么。

我试过的

我正在使用csv.writerow()将它们全部放在同一行中。 但我需要它们在专栏中。

试图修复我切换到csv.writerows()将它们放在列中,但每个数字都在一个新的行中,与下一个分开。

有人知道为什么吗?

代码

class readingJ1Average:
    def readingJ1(filepath):
        with open(filepath, 'r') as f:
            j1 = f.readlines()[46:47]
            #Coverting list to a string
            j1_join = ('\n'.join(j1))
            #Pulling only average
            j1_value = j1_join[5:16]
            #Appending to a list
            j1_list.append(j1_value)


    def readingJ2(filepath):
        with open(filepath, 'r') as f:
            j2 = f.readlines()[47:48]
            print(j2)
            #Coverting list to a string
            j2_join = ('\n'.join(j2))
            #Pulling only average
            j2_value = j2_join[5:16]
            #Appending to a list
            j2_list.append(j2_value)

    def readingJ3(filepath):
        with open(filepath, 'r') as f:
            j3 = f.readlines()[48:49]
            #Coverting list to a string
            j3_join = ('\n'.join(j3))
            #Pulling only average
            j3_value = j3_join[5:16]
            #Appending to a list
            j3_list.append(j3_value)

    def readingJ4(filepath):
        with open(filepath, 'r') as f:
            j4 = f.readlines()[48:49]
            #Coverting list to a string
            j4_join = ('\n'.join(j4))
            #Pulling only average
            j4_value = j4_join[5:16]
            #Appending to a list
            j4_list.append(j4_value)

    def readingJ5(filepath):
        with open(filepath, 'r') as f:
            j5 = f.readlines()[49:50]
            #Coverting list to a string
            j5_join = ('\n'.join(j5))
            #Pulling only average
            j5_value = j5_join[5:16]
            #Appending to a list
            j5_list.append(j5_value)

    def readingJ6(filepath):
        with open(filepath, 'r') as f:
            j6 = f.readlines()[50:51]
            #Coverting list to a string
            j6_join = ('\n'.join(j6))
            #Pulling only average
            j6_value = j6_join[5:16]
            #Appending to a list
            j6_list.append(j6_value)

    def readingJ7(filepath):
        with open(filepath, 'r') as f:
            j7 = f.readlines()[51:52]
            #Coverting list to a string
            j7_join = ('\n'.join(j7))
            #Pulling only average
            j7_value = j7_join[5:16]
            #Appending to a list
            j7_list.append(j7_value)

#Beginning main code
j1_list = []
j2_list = []
j3_list = []
j4_list = []
j5_list = []
j6_list = []
j7_list = []

for file in os.listdir():
#check if file is in text format or not
if file.endswith(".ls"):
    filepath = f"{path}\{file}"
    #calling the read function
    readingJ1Average.readingJ1(filepath)

for file in os.listdir():
#check if file is in text format or not
if file.endswith(".ls"):
    filepath = f"{path}\{file}"
    #calling the read function
    readingJ1Average.readingJ2(filepath)

for file in os.listdir():
#check if file is in text format or not
if file.endswith(".ls"):
    filepath = f"{path}\{file}"
    #calling the read function
    readingJ1Average.readingJ3(filepath)

for file in os.listdir():
#check if file is in text format or not
if file.endswith(".ls"):
    filepath = f"{path}\{file}"
    #calling the read function
    readingJ1Average.readingJ4(filepath)

for file in os.listdir():
#check if file is in text format or not
if file.endswith(".ls"):
    filepath = f"{path}\{file}"
    #calling the read function
    readingJ1Average.readingJ5(filepath)

for file in os.listdir():
#check if file is in text format or not
if file.endswith(".ls"):
    filepath = f"{path}\{file}"
    #calling the read function
    readingJ1Average.readingJ6(filepath)

for file in os.listdir():
#check if file is in text format or not
if file.endswith(".ls"):
    filepath = f"{path}\{file}"
    #calling the read function
    readingJ1Average.readingJ7(filepath)

with open('C:/Users/DunningJ3/Desktop/sample.csv', 'w') as wf:
write = csv.writer(wf)
write.writerows(j1_list)
#TXT file to Excel

快速的答案是您需要将行转换为字符串,而不是将其保留为列表或使用矩阵。 但首先你需要保持简单,清除所有代码异味并遵循最佳实践,否则将很难找到解决方案。

csv.writerows() 需要一个行列表,但您想转置它们,因此我们可以通过使用矩阵或字符串数组来解决这个问题。 对于这两个新项目(数字列表或字符串),原始 csv 的每一行都采用相同的 position 生成。

假设原始 csv 是“A”并且包含“a(ij)”形式的项目。 您将构建一个新的“A'”,其中的项目是“a'(ji)”并且 csv.writerows() 期望:

[ 
  [a'(00), a'(01), ..., a'(0i)]
  [a'(10), a'(11), ..., a'(1i)]
  ...
  [a'(j0), a'(j1), ..., a'(ji)
]

这是一种转置矩阵 btw

import csv

matrix = []

def init_matrix(total_lines):
    for i in range(total_lines):
        matrix.append([])

def readAll(filepath, csv_separator):
    with open(filepath, 'r') as f:
        lines = f.readlines()
        total_rows = len(lines)
        total_cols = len(lines[0].split(csv_separator))
        print('Total Rows ', total_rows)
        print('Total Cols ', total_cols)
        init_matrix(total_cols)
        for j in range(total_rows):
            line = lines[j].rstrip()
            elements = line.split(csv_separator)
            for i in range(total_cols):
                matrix[i].append(elements[i])


def main():
    filepath = f"{'test.csv'}"
    readAll(filepath, ',')
    with open('result.csv', 'w') as wf:
        write = csv.writer(wf)
        write.writerows(matrix)

main()

这里是样本 test.csv 文件

a,1,2,3,4,5,6,7,8,9,0
b,1,2,3,4,5,6,7,8,9,0
c,1,2,3,4,5,6,7,8,9,0
d,1,2,3,4,5,6,7,8,9,0
e,1,2,3,4,5,6,7,8,9,0
f,1,2,3,4,5,6,7,8,9,0
g,1,2,3,4,5,6,7,8,9,0

output 将是

a,b,c,d,e,f,g
1,1,1,1,1,1,1
2,2,2,2,2,2,2
3,3,3,3,3,3,3
4,4,4,4,4,4,4
5,5,5,5,5,5,5
6,6,6,6,6,6,6
7,7,7,7,7,7,7
8,8,8,8,8,8,8
9,9,9,9,9,9,9
0,0,0,0,0,0,0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM