csv 是否有一种方法可以在写入行后立即修改并写入行?

tjrkku2a  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(140)

我尝试通过插入行来修改csv,但在关闭CSV之前,还要循环迭代以将附加列附加到CSV。我尝试了各种不同的方法,但似乎一旦完成writerows函数,下一步就不会处理任何writerows。有没有这样做的方法,或者我必须保存writerows结果,重新打开CSV文件,然后完成追加?我已经将rows插入CSV,然后注解掉output.writerows(rows)for循环在这种情况下确实有效。但是,插入writerows后,它不再像我希望的那样工作,因为它跳过了在函数过程中编写的任何内容。
下面是我一直在使用的一些示例代码:

import csv
import itertools
import uuid
from datetime import datetime

rows = [[1000000, 'Test', 'Test', 179, 1111, 222, 5, 'Test', 'Test', 1111, 'Test', 222, 'Test', 1111, 22222, 'Test', '', 1, 2],
        [1000000, 'Test', 'Test', 179, 1111, 222, 5, 'Test', 'Test', 1111, 'Test', 222, 'Test', 1111, 22222, 'Test', '', 1, 2],
        [1000000, 'Test', 'Test', 179, 1111, 222, 5, 'Test', 'Test', 1111, 'Test', 222, 'Test', 1111, 22222, 'Test', '', 1, 2],
        [1000000, 'Test', 'Test', 179, 1111, 222, 5, 'Test', 'Test', 1111, 'Test', 222, 'Test', 1111, 22222, 'Test', '', 1, 2],
        [1000000, 'Test', 'Test', 179, 1111, 222, 5, 'Test', 'Test', 1111, 'Test', 222, 'Test', 1111, 22222, 'Test', '', 1, 2],
        [1000000, 'Test', 'Test', 179, 1111, 222, 5, 'Test', 'Test', 1111, 'Test', 222, 'Test', 1111, 22222, 'Test', '', 1, 2],
        [1000000, 'Test', 'Test', 179, 1111, 222, 5, 'Test', 'Test', 1111, 'Test', 222, 'Test', 1111, 22222, 'Test', '', 1, 2],
        [1000000, 'Test', 'Test', 179, 1111, 222, 5, 'Test', 'Test', 1111, 'Test', 222, 'Test', 1111, 22222, 'Test', '', 1, 2],
        [1000000, 'Test', 'Test', 179, 1111, 222, 5, 'Test', 'Test', 1111, 'Test', 222, 'Test', 1111, 22222, 'Test', '', 1, 2]]

def _sanitize_report(source_file, dest_file, append_timestamp, timestamp_format, append_filename, file,
                        append_id):
    with open(source_file, 'r') as report:
        reader = csv.reader(report)
        with open(dest_file, 'w') as output_file:
            data_rows = 0
            output = csv.writer(output_file)
            output.writerows(rows)
            for index, row in enumerate(reader):
                if append_timestamp and append_filename and append_id:
                    output.writerow(itertools.chain([datetime.today().strftime(timestamp_format)],
                                                    [str(file).replace(file[0:3], '')],
                                                    [uuid.uuid4()]))
                elif append_timestamp and append_filename:
                    output.writerow(itertools.chain([datetime.today().strftime(timestamp_format)],
                                                    [str(file).replace(file[0:3], '')]))
                elif append_timestamp and append_id:
                    output.writerow(itertools.chain([datetime.today().strftime(timestamp_format)], [uuid.uuid4()]))
                elif append_filename and append_id:
                    output.writerow(itertools.chain([str(file).replace(file[0:3], '')], [uuid.uuid4()]))
                elif append_timestamp:
                    output.writerow(itertools.chain( [datetime.today().strftime(timestamp_format)]))
                elif append_filename:
                    output.writerow(itertools.chain([str(file).replace(file[0:3], '')]))
                elif append_id:
                    output.writerow(itertools.chain([uuid.uuid4()]))
                else:
                    output.writerow([value.replace('(not set)', '') for value in row])
                data_rows += 1

_sanitize_report('test.csv', 'test_' + str(uuid.uuid4()) + '.csv',
                    append_timestamp=True, timestamp_format=datetime.utcnow().isoformat() + 'Z',
                    append_filename=True, file='123Test_success', append_id=True)

我所寻找的最终结果是让用户决定需要追加到结果中的内容,并将文件保存到一个新的位置。这可能在一个函数中完成吗?还是必须将其分解?我尝试了多种不同的方法,但都没有成功,我已经这样做了大约一个星期了。
在这方面的任何帮助将是令人难以置信的感激!

yebdmbv4

yebdmbv41#

当您在调用writerows()之后,又调用了若干次writerrow()时,会发生什么情况?

rows = [
    ["r1c1", "r1c2", "r1c3"],
    ["r2c1", "r2c2", "r2c3"],
    ["r3c1", "r3c2", "r3c3"],
]

with open("output.csv", "w", newline="") as f_out:
    writer = csv.writer(f_out)
    writer.writerows(rows)
    writer.writerow(["r4c1", "r4c2", "r4c3"])
    writer.writerow(["r5c1", "r5c2", "r5c3"])

发生这种情况:

r1c1,r1c2,r1c3
r2c1,r2c2,r2c3
r3c1,r3c2,r3c3
r4c1,r4c2,r4c3
r5c1,r5c2,r5c3

如果调用writerows()时列表中已经有了单独的行,或者调用writerrow()迭代行列表,也会发生同样的情况。
writerrow()写入单个行,而writerows()写入行列表。
如果你想有选择地在数据中添加一些列,你需要在调用writerrow()或writerows()之前将这些列添加到行中。

...
ts = datetime.today()
file_id = "foo_1"
for row in rows:
    if append_timestamp:
        row.append(ts)
    if append_id:
        row.append(file_id)
    ...
    writer.writerow(row)

相关问题