Home > Software engineering >  How to read csv file to get output without list but in normal String?
How to read csv file to get output without list but in normal String?

Time:10-27

I would like to ask how to change code to get output:

Nigel;UK;19
John;US;22
Carol;Germany;26

no this input (is it list?):

['Nigel', 'UK', '19']
['John', 'US', '22']
['Carol', 'Germany', '26']

code:

import csv

with open('friends.csv', 'r') as source:
    reader = csv.reader(source)

    for line in reader:
        print(line)

I think that now exist some instructions for it but I did not find it.
Thank you

CodePudding user response:

You get the output as a list because that's what csv.reader() does! It reads each line of a csv file, converts it to a list taking into account commas and escaping rules, and returns that list.

If you don't care about each individual element of the csv file, just read the file as a regular file:

with open("filename.csv", "r") as f:
    for line in f:
        print(line, end="")

the end="" argument prevents print() from adding its own newline characters, since the line from the file already includes the newline character

Alternatively, you can still read it as a csv file, but str.join() the resulting list before printing it. Use this if you are using the rows of the csv file as a list somewhere else, but you just want to print the file here

with open('friends.csv', 'r') as source:
    reader = csv.reader(source)
    for line in reader:
        print(";".join(line))

CodePudding user response:

Try unpacking the list elements via the * operator, and pass a custom separator to print:

import csv

with open('friends.csv', 'r') as source:
    reader = csv.reader(source)

    for line in reader:
        print(*line, sep=';')

Result:

Nigel;UK;19
John;US;22
Carol;Germany;26

An easier (and more efficient) approach would be to read in file contents as a string, and then replace all commas with a colon:

with open('friends.csv', 'r') as source:
    print(source.read().replace(',', ';'))

Note, this assumes the contents of your friends.csv is as follows:

Nigel,UK,19
John,US,22
Carol,Germany,26
  • Related