使用 python 将一个 csv 文件的内容附加到另一个文件

发布于 2024-09-09 18:51:35 字数 1119 浏览 3 评论 0原文

我有 2 个 csv 文件:

  • output.csv
  • 、output1.csv

、output.csv 有 5 列标题。
output1.csv 包含大约 40 列不同类型的数据。

我需要将output1.csv的所有内容附加到output.csv。我该怎么做?
有人可以给我一个关于如何去做的提示吗???
我有以下代码:

reader=csv.DictReader(open("test.csv","r"))
allrows = list(reader)

keepcols = [c for c in allrows[0] if all(r[c] != '0' for r in allrows)]

print keepcols
writer=csv.DictWriter(open("output.csv","w"),fieldnames='keepcols',extrasaction='ignore')
writer.writerows(allrows)

    with open("test1.csv","r") as f:
        fields=next(f).split()
        # print(fields)
        allrows=[]
        for line in f:
            line=line.split()
            row=dict(zip(fields,line))
            allrows.append(row)
            # print(row)
        keepcols = [c for c in fields if any(row[c] != '0' for row in allrows)]
        print keepcols
        writer=csv.DictWriter(open("output1.csv","w"),fieldnames=keepcols,extrasaction='ignore')
        writer.writerows(allrows)

test.csv 生成 output.csv
test1.csv 生成 output1.csv

我试图看看是否可以使两个文件在同一个文件中生成我的输出。

I have 2 csv files:

  • output.csv
  • output1.csv

output.csv has a 5 columns of titles.
output1.csv has about 40 columns of different types of data.

I need to append all the content of output1.csv to output.csv. How can I do this?
could somebody please give me a hint on how to go about it ???
i have the following code :

reader=csv.DictReader(open("test.csv","r"))
allrows = list(reader)

keepcols = [c for c in allrows[0] if all(r[c] != '0' for r in allrows)]

print keepcols
writer=csv.DictWriter(open("output.csv","w"),fieldnames='keepcols',extrasaction='ignore')
writer.writerows(allrows)

    with open("test1.csv","r") as f:
        fields=next(f).split()
        # print(fields)
        allrows=[]
        for line in f:
            line=line.split()
            row=dict(zip(fields,line))
            allrows.append(row)
            # print(row)
        keepcols = [c for c in fields if any(row[c] != '0' for row in allrows)]
        print keepcols
        writer=csv.DictWriter(open("output1.csv","w"),fieldnames=keepcols,extrasaction='ignore')
        writer.writerows(allrows)

test.csv generates output.csv
test1.csv generates output1.csv

i m trying to see if i can make both files generate my output in the same file..

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

泪眸﹌ 2024-09-16 18:51:35

如果我正确理解你的问题,你想要创建一个包含 41 列的 csv - output.csv 中的 1 列,然后是 output1.csv 中的 40 列。
我假设它们具有相同的行数(如果不是 - 必要的行为是什么?)

尝试使用 csv 模块:

import csv
reader = csv.reader(open('output.csv', 'rb'))
reader1 = csv.reader(open('output1.csv', 'rb'))
writer = csv.writer(open('appended_output.csv', 'wb'))
for row in reader:
    row1 = reader1.next()
    writer.writerow(row + row1)

如果您的 csv 文件使用特殊分隔符或引号字符进行格式化,则可以使用 csv 的可选关键字参数。 reader 和 csv.writer 对象。
有关详细信息,请参阅 Python 的 csv 模块文档...

编辑:添加了 'b' 标志,如建议。

If I understand your question correctly, you want to create a csv with 41 columns - the 1 from output.csv followed by the 40 from output1.csv.
I assume they have the same number of rows (if not - what is the necessary behavior?)

Try using the csv module:

import csv
reader = csv.reader(open('output.csv', 'rb'))
reader1 = csv.reader(open('output1.csv', 'rb'))
writer = csv.writer(open('appended_output.csv', 'wb'))
for row in reader:
    row1 = reader1.next()
    writer.writerow(row + row1)

If your csv files are formatted with special delimiters or quoting characters, you can use the optional keyword arguments for the csv.reader and csv.writer objects.
See Python's csv module documentation for details...

EDIT: Added 'b' flag, as suggested.

_畞蕅 2024-09-16 18:51:35

最近的讨论看起来与您正在寻找的内容非常相似,除了那里的OP想要连接mp3文件。

编辑:

import os, sys
target = '/path/to/target'
src1 = '/path/to/source1.csv'
src2 = '/path/to/source2.csv'
tf = open(target, 'a')
tf.write(open(src1).read())
tf.write(open(src2).read())
tf.close()

试试这个,这应该可行,因为你只想做相当于 cat src1 src2 > > shell命令的目标

This recent discussion looks very similar to what you are looking for except that the OP there wanted to concatenate mp3 files.

EDIT:

import os, sys
target = '/path/to/target'
src1 = '/path/to/source1.csv'
src2 = '/path/to/source2.csv'
tf = open(target, 'a')
tf.write(open(src1).read())
tf.write(open(src2).read())
tf.close()

try this, this should work since you simply want to do the equivalent of cat src1 src2 > target of shell command

梦开始←不甜 2024-09-16 18:51:35

“我需要将output1.csv的所有内容附加到output.csv。” ...从字面上看,这意味着将每一行写入第一个文件中,然后写入第二个文件中的每一行。这就是你想要的吗??

什么的标题?另一个文件中的 40 列?如果是这样,则假设您希望将标题写为一行列标题:

import csv
titles = [x[0] for x in csv.reader(open('titles.csv', 'rb'))]
writer = csv.writer(open('merged.csv', 'wb'))
writer.writerow(titles)
for row in csv.reader(open('data.csv', 'rb')):
    writer.writerow(row)

"I need to append all the content of output1.csv to output.csv." ... taken literally that would mean write each row in the first file followed by each row in the second file. Is that what you want??

titles of what? the 40 columns in the other file?? If this is so, then assuming that you want the titles written as a row of column headings:

import csv
titles = [x[0] for x in csv.reader(open('titles.csv', 'rb'))]
writer = csv.writer(open('merged.csv', 'wb'))
writer.writerow(titles)
for row in csv.reader(open('data.csv', 'rb')):
    writer.writerow(row)
一世旳自豪 2024-09-16 18:51:35

如果你想传递一个条件,你也可以使用阅读器的生成器:

import csv
def read_generator(filepath:str):
   with open(filepath, 'rb'):
     reader = csv.reader(f)
     for row in reader:
       if row[0] == condition:
         yield row

然后用以下命令写入:

writer = csv.writer(open("process.csv", "rb"))
write.writerow(read_generator(file_to_read.csv))

You could also use a generator from the reader if you want to pass a condition:

import csv
def read_generator(filepath:str):
   with open(filepath, 'rb'):
     reader = csv.reader(f)
     for row in reader:
       if row[0] == condition:
         yield row

and then write from that with:

writer = csv.writer(open("process.csv", "rb"))
write.writerow(read_generator(file_to_read.csv))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文