简体   繁体   中英

Python csv file creation

In one battle area, you are provided with a list of monsters to go along with your D&D game. You decide to create a program to read this information and process store additional information about these monsters.

The input Monsters.csv is also attached in this assignment. Write a script that reads this CSV file into Python and, for each monster in the list, adds the following columns for output

  • Level
  • Damage
  • Hit points

For Level, the following guidelines apply

  • Gnomes are level 1
  • Orcs are level 2
  • Skeletons are level 5
  • Giants are level 8

For Damage, the following apply

  • Gnomes can damage 1-3 hit points at random
  • Orcs can damage 2-7 hit points at random
  • Skeletons can damage 3-12 hit points at random
  • Giants can damage 4-24 hit points at random

For Hit points, the following apply

  • Gnomes can have 3-6 hit points at random
  • Orcs can have 4-8 hit points at random
  • Skeletons can have 6-12 hit points at random
  • Giants can have 12-20 hit points at random

The code should output to a file called New-Monsters.csv, which follows the guidelines from above, and will provide spreadsheet information (random where appropriate) like the following (attached in New-Monsters-SAMPLE.csv)

This is my assignment. The code that I have so far is...

import csv
 with open('Monsters.csv','w',newline='') as fp:
    a= csv.writer(fp,delimeter=',')
    data=[['Monster names','level','damage','hitpoints'],
          ['Gnome','1','3','6'],
          ['Orc','2','7','8'],
          ['Skeletons','5','12','12'],
          ['Giants','8','24','20']]
    a.writerows(data)

At this point, I'm getting a permission denied error on the with open monsters file line. How do I fix that and would this code work?

Take a look at using pandas . You can read in a csv file as a dataframe, and then process and add columns/rows.

import pandas as pd

# return level for name of monster
def level_map( name):
    return {
        'Gnome' : 1,
        'Orc' : 2,
        'Skeleton' : 5,
        'Giant' : 8
    }.get(p)

my_data = pd.read_csv("Monsters.csv", sep = ',', header=None)
my_data.columns =['Monster_name']

# process your data
my_data['Level'] = my_data["Monster_name"].apply(level_map)

f = open("output_file.csv", 'w')
f.write(my_data.to_csv(index = False))
f.close()

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM