简体   繁体   English

如何从新创建的csv文件列中添加?

[英]How do I add from a newly created csv file Column?

I would like to create a file in real time and add the values corresponding to the columns to an existing file in real time in the corresponding CSV file. 我想实时创建一个文件,并将与列对应的值实时添加到相应CSV文件中的现有文件中。

How can I add each of the CSV files that I generate in that program? 如何添加在该程序中生成的每个CSV文件?

I'll write down the code I'm using now. 我将写下现在使用的代码。

import csv

for i in range(10):
SD="Save datas(Angle)"+str(i)  ## 해당 각도별로 배열을 지정

SDArray1=str(SD)               ## 파일을 만들어준다

f=open(SDArray1+".csv","a+t")#  ## 이름을 만들어준 파일을 생성

csv_writer = csv.writer(f)
csv_writer.writerow([SD])
print("One loop has started")
f.close()#

for i in range(1,5):
    cdata=[i]
    f=open(SDArray1+".csv","a+t")

    csv_writer =csv.writer(f)
    csv_writer.writerow(cdata)

    print(cdata)
    f.close()#
    print("loop's finished!")

If you look at the code above, a certain file is created. 如果您看上面的代码,则会创建一个特定的文件。 I completed the next file, but I was wondering how to add columns to the file. 我完成了下一个文件,但是我想知道如何在文件中添加列。

csv.write_row() takes a complete row of columns - if you need more, add them to your cdata=[i] - fe cdata=[i,i*2,i*3,i*4] . csv.write_row()占据一csv.write_row()列的列-如果需要更多列,请将其添加到cdata=[i] -fe cdata=[i,i*2,i*3,i*4]

You should use with open() as f: for file manipulation , it is more resilient against errors and autocloses the file when leaving the with -block. 您应该with open() as f:来进行文件操作 ,它具有更强的抗错误能力,并在离开with -block时自动关闭文件。

Fixed: 固定:

import csv

# do not use i here and down below, thats confusing, better names are a plus
for fileCount in range(10):
    filename = "filename{}.csv".format(fileCount) # creates filename0.csv ... filename9.csv 

    with open(filename,"w") as f:#  # create file new
        csv_writer = csv.writer(f)
        # write headers
        csv_writer.writerow(["data1","data2","data3"])
        # write 4 rows of data
        for i in range(1,5):
            cdata=[(fileCount*100000+i*1000+k) for k in range(3)] # create 3 datapoints
            # write one row of data [1000,1001,1002] up to [9004000,9004001,9004002] 
            # for last i and fileCount
            csv_writer.writerow(cdata)

# no file.close- leaving wiht open() scope autocloses

Check what we have written: 检查我们写的内容:

import os
for d in sorted(os.listdir("./")):
    if d.endswith("csv"): 
        print(d,":") 
        print("*"*(len(d)+2)) 
        with open(d,"r") as f: 
            print(f.read()) 
        print("")

Output: 输出:

filename0.csv :
***************
data1,data2,data3
1000,1001,1002
2000,2001,2002
3000,3001,3002
4000,4001,4002


filename1.csv :
***************
data1,data2,data3
101000,101001,101002
102000,102001,102002
103000,103001,103002
104000,104001,104002

filename2.csv :
***************
data1,data2,data3
201000,201001,201002
[...snip the rest - you get the idea ...]     

filename9.csv :
***************
data1,data2,data3
901000,901001,901002
902000,902001,902002
903000,903001,903002
904000,904001,904002

To add a new column to an existing file: 要将新列添加到现有文件:

  • open old file to read 打开旧文件进行读取
  • open new file to write 打开新文件进行写入
  • read the old files header, add new column header and write it in new file 读取旧文件头,添加新列头并将其写入新文件
  • read all rows, add new columns value to each row and write it in new file 读取所有行,向每行添加新的列值,并将其写入新文件

Example: 例:

Adding the sum of column values to the file and writing as new file: 将列值的总和添加到文件中并作为新文件写入:

filename = "filename0.csv"
newfile =  "filename0new.csv"

# open one file to read, open other (new one) to write
with open(filename,"r") as r, open(newfile,"w") as w:
    reader = csv.reader(r)
    writer = csv.writer(w)

    newHeader = next(reader)   # read the header
    newHeader.append("Sum")    # append new column-header
    writer.writerow(newHeader) # write header

    # for each row: 
    for row in reader:
        row.append(sum(map(int,row)))   # read it, sum the converted int values
        writer.writerow(row)            # write it

# output the newly created file:
with open(newfile,"r") as n:
    print(n.read())

Output: 输出:

data1,data2,data3,Sum
1000,1001,1002,3003
2000,2001,2002,6003
3000,3001,3002,9003
4000,4001,4002,12003

暂无
暂无

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

相关问题 如何设置新创建的csv文件的位置? - How do i set the location of the newly created csv file? 尝试向新创建的 csv 文件添加列标题 - Attempting to add a column heading to the newly created csv file 如何在从 csv 文件创建的 dataframe 中添加列名? - how to add column name in a dataframe created from a csv file? 如何从命令提示符 window 运行我新创建的 hello_world.py 文件? - How do I run my newly created hello_world.py file from a command prompt window? 如何在新创建的模块中从Odoo v8中的Javascript文件调用python函数? - How do I call a python function from Javascript file in Odoo v8 in a newly created module? 如何将新数据列添加到csv文件中 - How do I add a new column of data to a csv file 使用熊猫,如何将一个 csv 文件列转换为列表,然后使用创建的列表过滤不同的 csv? - Using pandas, how do I turn one csv file column into list and then filter a different csv with the created list? Pandas:如何使用现有列和新创建列中的先前行创建新列? - Pandas : How can I create new column using previous rows from existing column and newly created column? 如何将 pandas dataframe output 保存到新创建的文件夹中的 ZCC8D68C551C4A9A6D5313EDZDE 文件中? - How can I save pandas dataframe output to a CSV file in a newly created folder? 如何基于另一个 csv 文件向 csv 文件添加列? - How do I add a column to a csv file based on another csv file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM