Python | delimited text file to csv format
<p>I'm new to python but I'm having trouble reading a text file which contains data separated by "|" as the delimiter. How would I separate the file into columns in a CSV format.</p>

<pre><code>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)
</code></pre>

<p>This code gets rid of the <strong>|</strong> 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.</p>

<p>The <a href="https://docs.python.org/3/library/csv.html#csv.reader" rel="nofollow"><code>csv</code> module</a> allows you to read csv files with practically arbitrary delimiters.</p>

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

<p>If you really want to reformat the file, you can use the <code>csv.writer</code> directly:</p>

<pre><code>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)
</code></pre>

<hr>

<p>Note that your approach doesn't work because you <em>remove</em> the separator instead of replacing it. <code>data.replace("|","")</code> will replace each <code>|</code> with the empty string, i.e. <code>"foo|bar"</code> becomes <code>"foobar"</code>. You must replace the old separator with a <em>new</em> one, e.g. <code>data.replace("|", ",")</code>.</p>

python python-3.x