简体   繁体   English

Python | 分隔文本文件为csv格式

[英]Python | delimited text file to csv format

I'm new to python but I'm having trouble reading a text file which contains data separated by "|" 我是python的新手,但无法读取包含以“ |”分隔的数据的文本文件 as the delimiter. 作为分隔符。 How would I separate the file into columns in a CSV format. 如何将文件分成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)

This code gets rid of the | 此代码摆脱了| to a blank but all the data is just in one column now. 变为空白,但所有数据现在都在一列中。 How can I format this correctly? 如何正确格式化? I appreciate your help in advance. 非常感谢您的帮助。

The csv module allows you to read csv files with practically arbitrary delimiters. csv模块允许您使用几乎任意的定界符读取csv文件。

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

If you really want to reformat the file, you can use the csv.writer directly: 如果您确实要重新格式化文件,则可以直接使用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)

Note that your approach doesn't work because you remove the separator instead of replacing it. 请注意,您的方法无效,因为您删除了分隔符而不是替换了分隔符。 data.replace("|","") will replace each | data.replace("|","")将替换每个| with the empty string, ie "foo|bar" becomes "foobar" . 带有空字符串,即"foo|bar"变为"foobar" You must replace the old separator with a new one, eg data.replace("|", ",") . 您必须用新的分隔符替换旧的分隔符,例如data.replace("|", ",")

The simplest way with your code would be to replace "|" 您的代码最简单的方法是替换“ |” with "," rather than removing "|" 用“,”而不是删除“ |”

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

You're importing the csv module, but aren't using it. 您正在导入csv模块,但未使用它。 Make use of csv.reader 利用csv.reader

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

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

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