110 likes | 119 Views
Learn how to create, write, and read CSV files in computer programming. Explore examples and tasks related to CSV file handling for data science purposes.
E N D
Open your notepad (or other text editor). • Write the following and save. • 3,2,5 • 1,7,13 • Rename the extension to .csv • Open with excel. • Open with notepad.
Comma-Separated Values (CSV) A text file that has its values as numbers or strings, separated by commas and new lines. Note: This is not excel workbook format.
Example 1 (Write file) w = write #include <stdio.h> main() { FILE *fp; fp = fopen(“file.txt”, “w”); fprintf(fp,“Hello”); fclose(fp); } • File handle • Open file • Write • Close file
Example 1 (Write file) #include <stdio.h> main() { FILE *fp; fp = fopen(“file.csv”, “w”); fprintf(fp,“3,2,5\n”); fprintf(fp,“1,7,13\n”); fclose(fp); } • File handle • Open file • Write • Close file
Example 2 (Read file) #include <stdio.h> main() { int a,b,c; FILE *fp; fp = fopen(“file.csv”, “r”); fscanf(fp,“%d,%d,%d”,&a,&b,&c); fscanf(fp,“%d,%d,%d”,&a,&b,&c); fclose(fp); }
Example 3 (Read file) #include <stdio.h> main() { int a,b,c,d; FILE *fp; fp = fopen(“file.csv”, “r”); d = fscanf(fp,“%d,%d,%d”,&a,&b,&c); d = fscanf(fp,“%d,%d,%d”,&a,&b,&c); d = fscanf(fp,“%d,%d,%d”,&a,&b,&c); fclose(fp); } Check out the return from scanf
Data Science Investigate the Pokemon database.
Task 1 Print all the pokemon’s name on the screen. Read header once. Use loop for each subsequence lines. Instead of using %s for string Use %[^\n,]
Task 2 Write a program to print the pokemon’s name that has the highest HP. (for Student ID 01-10) Attack (for Student ID 11-20) Defense (for Student ID 21-30) Total (for Student ID 31-) Hint: Use find minimum in lecture 6 (array)