0

I am using the following code

import csv

with open('skill.csv', 'r') as csv_file:
    csv_reader = csv.DictReader(csv_file)

    # next(csv_reader)

    for line in csv_reader:
        print(line)

Here is what the csv contains:

Skill,amount_of_skill
First aid,50
Stealth,40

It outputs:

OrderedDict([('Skill', 'First aid'), ('amount_of_skill', '50')])
OrderedDict([('Skill', 'Stealth'), ('amount_of_skill', '40')])

How do I get it to just say:

First Aid    50
Stealth   40
1
  • Why do you read the lines in a dictionary in the first place? Commented Nov 26, 2020 at 19:09

4 Answers 4

3

You are reading as a dict but you need a simple csv.

Here is as it should be:

import csv
with open('skill.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    next(csv_reader) #to skip header
    for line in csv_reader:
        print('  '.join(line))
Sign up to request clarification or add additional context in comments.

Comments

0

The problem with your code is that you don't access the values of the dictionary, you just print the dictionary that holds the data for each line.

with open("skill.csv", "r") as csv_file:
    reader = csv.DictReader(csv_file, delimiter=",")
    for line in reader:
        print(" ".join(line.values()))

Output:

First aid 50
Stealth 40

You could also use the unpacking operator (*) in the print statement:

print(*line.values())

Comments

0

You are reading the csv file into a dictionary.

You don't need any library to read the csv.. You can just open the file and split the fields by comma:

with open('skill.csv', 'r') as csv_file:
    csv_reader = csv_file.readlines()


for line in csv_reader:
    print(line.replace(',', ' '))

Output:

First aid 50
Stealth 40

Comments

0

Purely for fun ... if you wanted to smash it all into one line, you could do:

print(*[i.replace(',', ' ') for i in open('skills.csv').readlines()[1:]], sep='')

Output:

First aid 50
Stealth 40

Readable ... not really. Fun? Yes!


Something more readable:

with open('skills.csv') as f:
    lines = f.readlines()[1:]

print(*[i.replace(',', ' ') for i in lines], sep='')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.