簡體   English   中英

'OrderedDict' 並且 CSV 文件中沒有換行符

[英]'OrderedDict' and no line breaks in the CSV file

我想在迭代中使用outFile.write(str(line))從另一個 CSV 文件創建一個 CSV 文件。 但是這種方法使文件像:

OrderedDict([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')])OrderedDict([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')])OrderedDict(...

在開頭添加OrderdedDict並且沒有換行符。 這應該類似於(與 Input CSV 相同):

key1, key2, key3
value1, value2, value3
value1, value2, value3
...

我寫的代碼是:

with open(path_to_read_csv_file, "r") as csv_file:
    csv_reader = csv.DictReader(csv_file, delimiter=',')
    for line in csv_reader:
        if [condition]:
            outFile.write(str(line))
        else:
            continue

有什么建議嗎?

使用 DictWriter

import csv
from io import StringIO

data = """\
key1, key2, key3
value1, value2, value3
value1, value2, value3
"""
f = StringIO(data)
reader = csv.DictReader(f)
o = StringIO()
writer = csv.DictWriter(o, reader.fieldnames)
writer.writeheader()
for d in reader:
    writer.writerow(d)

o.seek(0)
print(o.read())

考慮使用pandas 在處理表格數據時使用它是很好的。 有許多有用的功能(也過濾數據)。

import pandas as pd
path_to_input_csv = 'example_csv.csv'
path_to_output_csv = 'example_csv_out.csv'
df = pd.read_csv(path_to_input_csv, sep=',', header=0)
is_ok = df['key2'] == 'good_value'
df = df[is_ok]
df.to_csv(path_to_output_csv, sep=',', header=True, index=False)

我的輸入文件:

key1,key2,key3
value1a,good_value,value3a
value1b,bad_value,value3b

輸出文件:

key1,key2,key3
value1a,good_value,value3a

在這段代碼中

with open(path_to_read_csv_file, "r") as csv_file:
    csv_reader = csv.DictReader(csv_file, delimiter=',')
    for line in csv_reader:
        if [condition]:
            outFile.write(str(line))
        else:
            continue

您正在迭代csv_reader ,每次迭代都會生成一個dictionary 使用 csv 模塊的工具將輸出寫回 csv 文件會更好:

with open(path_to_read_csv_file, "r") as csv_file, open('myfile.csv', 'w', newline='') as outfile
    csv_reader = csv.DictReader(csv_file, delimiter=',')
    # Get the column headers.
    fieldnames = list(next(csv_reader).keys())
    # rewind to the beginning of the file.
    csv_file.seek(0)
    csv_writer = csv.DictReader(f, fieldnames=fieldnames, delimiter=',')
    for line in csv_reader:
        if [condition]:
            csv_writer.write(line)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM