简体   繁体   English

读取然后写入 CSV 文件行 - Python3

[英]Reading then Writing Lines of CSV file - Python3

I have recently written scripts to web scrape and download different files that I need from county property appraiser websites.我最近编写了脚本来进行网络抓取并从县财产估价师网站下载我需要的不同文件。 I now would like to add code that can read the first 2 lines and write them to a new CSV file in order for me to have some observability if any field names are added/deleted/changed.我现在想添加可以读取前 2 行并将它们写入新的 CSV 文件的代码,以便在添加/删除/更改任何字段名称时有一些可观察性。 I think I'm pretty close but I've run into an error that I can't seem to figure out.我想我已经很接近了,但我遇到了一个我似乎无法弄清楚的错误。 Here is my code:这是我的代码:

with open('OsceolaTaxParcels09012020.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file)

    for i in range(2):
        rows = print(csv_reader.__next__())

    with open('Osceola_Field_Check09152020.csv', 'w') as new_file:
        csv_writer = csv.writer(new_file)

        for i in range(2):
            csv_writer.writerows(rows)

The error I keep getting is on the last line, Type Error: writerows() argument must be iterable .我不断收到的错误在最后一行, Type Error: writerows() argument must be iterable I figured that the 'rows' variable would be iterable because it contains the first two lines of the original csv file, but alas it is not.我认为 'rows' 变量是可迭代的,因为它包含原始 csv 文件的前两行,但可惜不是。

Eventually, I would like to write code to compare two CSV files to each other to easily check for field changes;最后,我想编写代码来比较两个 CSV 文件,以便轻松检查字段更改; but that's a whole other can of worms.但那是另外一罐蠕虫。

Use writerow使用writerow

Ex:前任:

with open('OsceolaTaxParcels09012020.csv', 'r') as csv_file, open('Osceola_Field_Check09152020.csv', 'w', newline="") as new_file:
    csv_reader = csv.reader(csv_file)
    csv_writer = csv.writer(new_file)
 
    next(csv_reader) # Skip Header
    for _ in range(2):  # Iterate next 2 rows.
        csv_writer.writerow(next(csv_reader))    # Write Row

You do not need to use the csv module if you are trying to write the first two lines from one file to another file.如果您尝试将前两行从一个文件写入另一个文件,则不需要使用csv模块。 You can use pathlib for high-level file operations to read from one file and write to another.您可以使用pathlib进行高级文件操作,以读取一个文件并写入另一个文件。

from pathlib import Path

data = """\
a,b,c
1,2,3
0,0,1
"""

# Write example data to file.
p = Path("data.csv")
p.write_text(data)

# Read contents.
file_contents = p.read_text()
all_lines = file_contents.splitlines()
first_two_lines = all_lines[:2]

# Write to a new file.
output = Path("output.csv")
output.write_text("\n".join(first_two_lines))

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

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