k10a
k10a

Reputation: 1087

Want to convert the csv file from line break mode to be separated by comma

Currently the csv file is saved in line break mode. But it should be separated by comma for inputting these datas as an array.

The current csv file:

[email protected]
[email protected]
[email protected]

The ideal csv file:

[email protected], [email protected], [email protected]

The code:

def get_addresses():
    with open('./addresses.csv') as f:
        addresses_file = csv.reader(f)
        # Need to be converted

How can I convert it? I hope to use Python.

tried this.

with open('./addresses.txt') as input, open('./addresses.csv', 'w') as output:
    output.write(','.join(input.readlines()))
    output.write('\n')

the result:

[email protected]
,[email protected]
,[email protected]

Upvotes: 0

Views: 61

Answers (3)

tripleee
tripleee

Reputation: 189407

For this simple task, just read them into an array, then join the array on commas.

with open('./addresses.txt') as input, open('./addresses.csv', 'w') as output:
    output.write(','.join(input.read().splitlines()))
    output.write('\n')

This ignores any complications in the CSV formatting - if your data could contain commas (which are reserved as the field separator) or double quotes (which are reserved for quoting other reserved characters) you will want to switch to the proper csv module for output and perhaps for input.

Overwriting your input file is also an unnecessary complication, so I suggest you rename the input file to addresses.txt and use addresses.csv only for output.

Demo: https://repl.it/repls/AdequateStunningVideogames

Another common trick is to read one line at a time, and write a separator before each output except the first. This is more scalable for large input files.

with open blah blah blah ...:
    separator = ''  # for first line
    for line in input:
        output.write(separator)
        output.write(line)
        separator = ','  # for subsequent input lines
    output.write('\n')

Upvotes: 1

sushanth
sushanth

Reputation: 8302

with open('./addresses.txt') as f:
   print(",".join(f.read().splitlines()))

Upvotes: 2

David
David

Reputation: 1202

Load the original file into pandas using:

import pandas as pd
df = pd.read_csv({YOUR_FILE}, escapechar='\\')

Then export it back to .csv (by default this will be comma separated).

df.to_csv({YOUR_FILE})

Upvotes: 1

Related Questions