Guest User

Untitled

a guest
Jun 19th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. [TOC]
  2.  
  3. ## Python bits
  4.  
  5. ### CSV
  6. #### Open CSV
  7. ```python
  8. csv_data="""
  9. RUT,Name,LastName,E-mail,ISBN1,ISBN2
  10. 333,Pablo3,Alar3,mail3,0,0
  11. """
  12.  
  13. # recreate file
  14. from pathlib import Path
  15. Path('data.csv').write_text(csv_data)
  16.  
  17. import csv
  18. with open('data.csv') as f:
  19. data = [row for row in csv.reader(f)]
  20.  
  21. # Or using dict reader
  22. with open('data.csv') as f:
  23. data = [row for row in csv.DictReader(f)]
  24. ```
  25. #### Write CSV
  26. ```python
  27. with open('data.csv', 'w') as f:
  28. csv.writer(f).writerows(data)
  29.  
  30. # or using dict writer
  31. with open('data.csv', 'w') as f:
  32. writer_obj = csv.DictWriter(f, fieldnames=data[0].keys())
  33. writer_obj.writeheader()
  34. writer_obj.writerows(data)
  35. ```
  36. #### Edit a cell
  37. To change from
  38. ```
  39. RUT,Nombre,Apellido,E-mail,ISBN1,ISBN2
  40. 333,Pablo3,Alar3,mail3,0,0
  41. ```
  42. ```
  43. RUT,Nombre,Apellido,E-mail,ISBN1,ISBN2
  44. 333,Pablo3,Alar3,mail3,777,0
  45. ```
  46. ```python
  47. # open using dict reader
  48. for row in data:
  49. if row['RUT'] == rut:
  50. row['ISBN1'] = new_isbn1
  51. ```
  52.  
  53. ### Pandas
  54. #### CSV
  55. ```python
  56. import pandas as pd
  57. df = pd.read_csv('data.csv', index_col=0)
  58. df.loc[333,'ISBN1'] = 777
  59. print(df)
  60. # export example
  61. df.to_csv('temp2.txt')
  62. ```
  63. <!--stackedit_data:
  64. eyJoaXN0b3J5IjpbMTUyMjQxMDU1LDEwMTg2NTY4MDEsLTE5ND
  65. cxMDU3NDIsOTMwOTQ5MDc5LDM2ODY5MTk3LC0xOTcxMDE2NzA3
  66. LC0yMDYxNjc2NTUzXX0=
  67. -->
Add Comment
Please, Sign In to add comment