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
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))
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())
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
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='')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.