簡體   English   中英

如何讀取 csv 文件並將逗號從數字轉換為點?

[英]How to read a csv file and convert commas from the numbers to dot?

我編寫了此代碼來讀取 csv 文件:

    for file_to_open in filename:
        file_path = os.path.realpath(file_to_open)
        path_corrected = file_path.replace("file_mngt", "data")
        opened = open(path_corrected)
        reader = csv.reader(opened, delimiter = ";")
        header = next(reader)
        
        for row in reader:
           print(row)

結果是(對於每一行)是這樣的:

['8', 'Thorgal', '8,49', '3', '25,47']

我想將每一行中的每個逗號都轉換為一個點。 我在互聯網上查看,但他們都說我必須在 csv.reader 中放入“decimal = ','”,但它不起作用。 請幫忙。 謝謝。

使用列表理解並在列表的每個元素上調用replace()

print([item.replace(',', '.') for item in row])

如果您打算進一步處理數據,則可以使用 pandas:

import pandas as pd
df = pd.read_csv("your/file/path", delimiter=";", decimal=",")

我只會使用pandas庫。 它支持處理 csv 文件的所有基本功能,這使它變得更加容易。

你可以這樣做:

import pandas as pd

# read file with comma (,) as decimal separator
df = pd.read_csv(file_to_open, sep=";", decimal=",")

# write to file with dot (.) as decimal separator
df.to_csv("new_output_file.csv", sep=";", decimal=".", index=False)

afaik 默認的csv.reader不支持逗號小數,僅點/點。 您必須添加自己的自定義map或轉換功能。

看看convtools庫,它提供了大量的數據處理原語,並在幕后生成臨時代碼:

from convtools import conversion as c
from convtools.contrib.tables import Table

# e.g. without header, returns iterable of lists
rows = (
    Table.from_csv(path_corrected, dialect=Table.csv_dialect(delimiter=";"))
    # here we apply replace to every table cell
    .update_all(c.this().call_method("replace", ",", "."))
    .into_iter_rows(list)
)

# with header, returns iterable of dicts
rows = (
    Table.from_csv(
        path_corrected, header=True, dialect=Table.csv_dialect(delimiter=";")
    )
    .update_all(c.this().call_method("replace", ",", "."))
    .into_iter_rows(dict)
)

暫無
暫無

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

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