SHARE
TWEET

Untitled

a guest Sep 15th, 2019 101 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. """
  2. Assuming our CSV file (employee_birthday.csv) has the contents of
  3.  
  4. name,department,birthday month
  5. John Smith,Accounting,November
  6. Erica Meyers,IT,March
  7.  
  8. """
  9.  
  10. # Reading CSV Files with csv
  11.  
  12. import csv
  13.  
  14. with open('employee_birthday.txt') as csv_file:
  15.     csv_reader = csv.reader(csv_file, delimiter=',')
  16.     line_count = 0
  17.     for row in csv_reader:
  18.         if line_count == 0:
  19.             print(f'Column names are {", ".join(row)}')
  20.             line_count += 1
  21.         else:
  22.             print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
  23.             line_count += 1
  24.     print(f'Processed {line_count} lines.')
  25.    
  26. # Reading CSV files into a dictionar with csv
  27.  
  28. import csv
  29.  
  30. with open('employee_birthday.txt', mode='r') as csv_file:
  31.     csv_reader = csv.DictReader(csv_file)
  32.     line_count = 0
  33.     for row in csv_reader:
  34.         if line_count == 0:
  35.             print(f'Column names are {", ".join(row)}')
  36.             line_count += 1
  37.         print(f'\t{row["name"]} works in the {row["department"]} department, and was born in {row["birthday month"]}.')
  38.         line_count += 1
  39.     print(f'Processed {line_count} lines.')
  40.  
  41. # Writing CSV Files with csv
  42.  
  43. import csv
  44.  
  45. with open('employee_file.csv', mode='w') as employee_file:
  46.     employee_writer = csv.writer(employee_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
  47.  
  48.     employee_writer.writerow(['John Smith', 'Accounting', 'November'])
  49.     employee_writer.writerow(['Erica Meyers', 'IT', 'March'])
  50.    
  51. # Writing CSV File From a Dictionary with csv
  52.  
  53. import csv
  54.  
  55. with open('employee_file2.csv', mode='w') as csv_file:
  56.     fieldnames = ['emp_name', 'dept', 'birth_month']
  57.     writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
  58.  
  59.     writer.writeheader()
  60.     writer.writerow({'emp_name': 'John Smith', 'dept': 'Accounting', 'birth_month': 'November'})
  61.     writer.writerow({'emp_name': 'Erica Meyers', 'dept': 'IT', 'birth_month': 'March'})
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top