【问题标题】:Python | delimited text file to csv format蟒蛇 |分隔文本文件到 csv 格式
【发布时间】:2016-10-04 14:07:35
【问题描述】:

我是 python 新手,但我无法读取包含由“|”分隔的数据的文本文件作为分隔符。如何将文件分成 CSV 格式的列。

import csv
my_file_name = "NVG.txt"
cleaned_file = "cleanNVG.csv"

with open(my_file_name, 'r') as infile, open(cleaned_file, 'w') as outfile:
    data = infile.read()

    data = data.replace("|","")
    outfile.write(data)

此代码将 | 去掉为空白​​,但现在所有数据都只在一列中。如何正确格式化? 提前感谢您的帮助。

【问题讨论】:

  • 为什么要删除 |?你为什么不直接告诉csv 那是你的分隔符?即csv.reader(infile, delimiter='|')

标签: python python-3.x


【解决方案1】:

csv module 允许您读取带有几乎任意分隔符的 csv 文件。

with open(my_file_name, 'r', newline='') as infile:
    for line in csv.reader(infile, delimiter='|'):
        # do stuff

如果真的要重新格式化文件,可以直接使用csv.writer

with open(my_file_name, 'r', newline='') as infile, open(cleaned_file, 'w', newline='') as outfile:
    writer = csv.writer(outfile)
    for line in csv.reader(infile, delimiter='|'):
        writer.writerow(line)

请注意,您的方法不起作用,因为您删除分隔符而不是替换它。 data.replace("|","") 会将每个 | 替换为空字符串,即 "foo|bar" 变为 "foobar"。您必须用 new 替换旧分隔符,例如data.replace("|", ",").

【讨论】:

  • 哦,好的!谢谢!数据现在在他们的列中,但之后会留下一个空行。所以第 1 行有数据,第 2 行是空白,第 3 行有数据,第 4 行是空白,依此类推......为什么要这样做?
  • @Cesar 将 writer 对象定义为writer = csv.writer(outfile, lineterminator="\n")
  • 其实没关系,**newline= ''** 搞砸了。这工作完美!
【解决方案2】:

使用您的代码最简单的方法是替换“|”使用“,”而不是删除“|”

data = data.replace("|", ",")

【讨论】:

    【解决方案3】:

    您正在导入 csv 模块,但没有使用它。使用csv.reader

    with open(my_file_name, 'r') as infile, open(cleaned_file, 'w') as outfile:
        reader = csv.reader(infile, delimiter='|')
    

    【讨论】:

      猜你喜欢
      • 2022-10-06
      • 1970-01-01
      • 2021-11-14
      • 1970-01-01
      • 2021-10-31
      • 1970-01-01
      • 1970-01-01
      • 2018-06-17
      • 2013-03-29
      相关资源
      最近更新 更多