简体   繁体   English

使用python在csv中更改分隔符

[英]Delimiter change in csv using python

I have a .csv file of around 30000 rows.我有一个大约 30000 行的 .csv 文件。 The default delimiter implemented is a semicolon.实现的默认分隔符是分号。 I created a small script with python that would convert that delimiter to comma and save it in the same file.我用 python 创建了一个小脚本,可以将该分隔符转换为逗号并将其保存在同一个文件中。 The script runs without any errors but does nothingnat the end.该脚本运行时没有任何错误,但最后什么也没做。 The delimiter is still a semicolon.分隔符仍然是分号。 The .txt file is created but it does not write back on the main file. .txt 文件已创建,但不会写回主文件。 The code I am using is as follows:我使用的代码如下:

import csv
from pathlib import Path
import os

cwd = os.getcwd()  # Get the current working directory (cwd)
files = os.listdir(cwd)  # Get all the files in that directory
print("Files in %r: %s" % (cwd, files))

with open('RadGridExport.csv', mode='r', encoding='utf-8') as infile:
    reader = csv.reader(infile, dialect="excel")
    with open('temp.txt', mode='w', encoding='utf-8') as outfile:
        writer = csv.writer(outfile, delimiter=',')
        writer.writerows(reader)

You have missed the delimiter while reading.您在阅读时错过了分隔符。 By default it looks for comma, since it is not the case you have to specify the delimiter:默认情况下,它查找逗号,因为您不必指定分隔符:

 reader = csv.reader(infile, dialect="excel",delimiter=";")

And you need not mention comma as delimiter while writing since it is the default.并且您在编写时无需提及逗号作为分隔符,因为它是默认值。

Or the easiest way is to use pandas package:或者最简单的方法是使用 pandas 包:


    import pandas as pd
    df=pd.read_csv(infile,sep=';')
    df.to_csv(infile,index=False)

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

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