Data input and output (I/O) lets you bring data into your program and save results. It helps you work with real-world data and share your findings.
You want to read a spreadsheet with sales data to analyze it.
You need to save your cleaned data to a file for later use.
You want to load a CSV file from the internet to explore it.
You have results from your analysis and want to export them to Excel.
You want to share your processed data with a teammate.
Syntax
Pandas
import pandas as pd
# Read data from a CSV file
df = pd.read_csv('filename.csv')
# Write data to a CSV file
df.to_csv('filename.csv', index=False)
Use pd.read_csv() to load data from CSV files.
Use df.to_csv() to save DataFrame data back to CSV files.
Examples
This reads data from 'data.csv' into a DataFrame called df.
Pandas
import pandas as pd
df = pd.read_csv('data.csv')
This saves the DataFrame df to 'output.csv' without row numbers.
Pandas
df.to_csv('output.csv', index=False)
You can also read Excel files using pd.read_excel().
Pandas
df = pd.read_excel('data.xlsx')
Save your DataFrame to an Excel file with to_excel().
Pandas
df.to_excel('output.xlsx', index=False)
Sample Program
This program creates a small table of names and ages, saves it to a CSV file, then reads it back and prints it. It shows how data I/O works in pandas.
Pandas
import pandas as pd
# Create a simple DataFrame
data = {'Name': ['Anna', 'Ben', 'Cara'], 'Age': [28, 34, 22]}
df = pd.DataFrame(data)
# Save DataFrame to CSV
csv_file = 'people.csv'
df.to_csv(csv_file, index=False)
# Read the CSV back into a new DataFrame
new_df = pd.read_csv(csv_file)
print(new_df)
OutputSuccess
Important Notes
Always check the file path and name when reading or writing files.
Use index=False when saving to avoid adding extra row numbers.
Data I/O lets you connect your code to real data and share results easily.
Summary
Data I/O means reading data into your program and saving it out.
It helps you work with real data files like CSV and Excel.
pandas has simple functions like read_csv and to_csv for this.
Practice
(1/5)
1. What does pandas.read_csv() do in data science?
easy
A. It reads data from a CSV file into a DataFrame.
B. It saves a DataFrame to a CSV file.
C. It creates a new empty DataFrame.
D. It deletes a CSV file from disk.
Solution
Step 1: Understand the function name
The function name read_csv suggests it reads CSV files.
Step 2: Recall pandas I/O functions
read_csv loads data from a CSV file into a pandas DataFrame for analysis.
Final Answer:
It reads data from a CSV file into a DataFrame. -> Option A
Quick Check:
read_csv = read data [OK]
Hint: Remember: read_csv reads data in, to_csv writes data out [OK]
Common Mistakes:
Confusing read_csv with to_csv
Thinking it creates empty DataFrame
Assuming it deletes files
2. Which of the following is the correct syntax to save a DataFrame df to a CSV file named data.csv?
easy
A. df.to_csv('data.csv')
B. df.read_csv('data.csv')
C. pandas.save_csv(df, 'data.csv')
D. df.save('data.csv')
Solution
Step 1: Identify the correct pandas method for saving
The method to save a DataFrame to CSV is to_csv.
Step 2: Check the syntax
The syntax is df.to_csv('filename.csv'), which matches df.to_csv('data.csv').
Final Answer:
df.to_csv('data.csv') -> Option A
Quick Check:
to_csv saves DataFrame to CSV [OK]
Hint: Use df.to_csv('filename.csv') to save data [OK]
Common Mistakes:
Using read_csv instead of to_csv
Using non-existent methods like save_csv or save
Wrong method call order
3. What will be the output of this code?
import pandas as pd
from io import StringIO
csv_data = 'name,age\nAlice,30\nBob,25'
df = pd.read_csv(StringIO(csv_data))
print(df.shape)
medium
A. (3, 3)
B. (3, 2)
C. (2, 3)
D. (2, 2)
Solution
Step 1: Understand the CSV data
The CSV string has 2 rows of data (Alice and Bob) and 2 columns (name, age).
Step 2: Check DataFrame shape
The shape is (rows, columns) = (2, 2).
Final Answer:
(2, 2) -> Option D
Quick Check:
2 rows and 2 columns = (2, 2) [OK]
Hint: Count rows and columns in CSV to find shape [OK]
Common Mistakes:
Counting header as a data row
Mixing rows and columns in shape
Confusing number of columns
4. Identify the error in this code snippet that tries to read a CSV file:
import pandas as pd
df = pd.read_csv('data.txt')
medium
A. read_csv cannot read text files
B. No error, code is correct
C. File extension should be .csv, not .txt
D. Missing import statement
Solution
Step 1: Examine the code for syntax issues
The code has proper import and correct read_csv call. No syntax errors.
Step 2: Understand file handling
pandas read_csv reads files based on content, not extension. 'data.txt' works if it contains CSV data.
Final Answer:
No error, code is correct -> Option B
Quick Check:
read_csv ignores file extension [OK]
Hint: File extension (.csv or .txt) doesn't matter for read_csv if format is correct [OK]
Common Mistakes:
Insisting on .csv extension only
Believing read_csv can't handle .txt files
Overlooking the present import statement
5. You have a DataFrame df with columns ['A', 'B', 'C']. You want to save only columns A and C to a CSV file named subset.csv. Which code correctly does this?
hard
A. df.to_csv('subset.csv', columns=['A', 'C'])
B. df.to_csv('subset.csv', cols=['A', 'C'])
C. df[['A', 'C']].to_csv('subset.csv', index=False)
D. df.to_csv('subset.csv').select(['A', 'C'])
Solution
Step 1: Recall to_csv column selection
Slicing df[['A', 'C']] creates a subset DataFrame with only desired columns.
Step 2: Proper saving syntax
df[['A', 'C']].to_csv('subset.csv', index=False) saves exactly A and C without index column.
Step 3: Evaluate alternatives
df.to_csv('subset.csv', columns=['A', 'C']) saves index + A + C (extra column). df.to_csv('subset.csv', cols=['A', 'C']) invalid cols param. df.to_csv('subset.csv').select(['A', 'C']) invalid method chain.
Final Answer:
df[['A', 'C']].to_csv('subset.csv', index=False) -> Option C
Quick Check:
df[cols].to_csv(index=False) excludes index [OK]
Hint: df[['A','C']].to_csv('subset.csv', index=False) for only those columns [OK]
Common Mistakes:
Using columns= without index=False (adds index column)
Using invalid cols parameter
Chaining non-existent .select() method
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.