Reading and writing files is one of the most important tasks in data analysis. Pandas provides built-in functions to import and export data from different file formats such as CSV, Excel, JSON, and text files. These functions help data analysts load datasets for analysis and save processed data efficiently. In this chapter, you’ll learn how to read, write, and manage files in Pandas using practical examples. Pandas Reading and Writing Files practice questions with solutions help to build concepts.
1. Python Program to Read a CSV File
Problem Statement
Write a Python program to read a CSV file using Pandas.
Python Solution
import pandas as pd
df = pd.read_csv("students.csv")
print(df)
Sample Output
Name Age Marks
0 Rahul 20 85
1 Aman 21 90
2 Priya 19 78
3 Sneha 22 88
Explanation
The read_csv() function imports data from a CSV file into a Pandas DataFrame.
Concepts Covered
read_csv()- CSV File
- Data Import
2. Python Program to Display the First Five Rows of a CSV File
Problem Statement
Write a Python program to read a CSV file and display only the first five rows.
Python Solution
import pandas as pd
df = pd.read_csv("students.csv")
print(df.head())
Sample Output
Name Age Marks
0 Rahul 20 85
1 Aman 21 90
2 Priya 19 78
3 Sneha 22 88
4 Rohit 23 95
Explanation
The head() function displays the first five rows after importing the dataset.
Concepts Covered
read_csv()head()- Data Preview
3. Python Program to Read Selected Columns from a CSV File
Problem Statement
Write a Python program to import only the Name and Marks columns from a CSV file.
Python Solution
import pandas as pd
df = pd.read_csv(
"students.csv",
usecols=["Name", "Marks"]
)
print(df)
Sample Output
Name Marks
0 Rahul 85
1 Aman 90
2 Priya 78
3 Sneha 88
Explanation
The usecols parameter imports only the specified columns, reducing memory usage and improving performance.
Concepts Covered
read_csv()usecols- Column Selection
4. Python Program to Read a CSV File with a Custom Index
Problem Statement
Write a Python program to use the Name column as the index while reading a CSV file.
Python Solution
import pandas as pd
df = pd.read_csv(
"students.csv",
index_col="Name"
)
print(df)
Sample Output
Age Marks
Name
Rahul 20 85
Aman 21 90
Priya 19 78
Sneha 22 88
Explanation
The index_col parameter assigns a column as the DataFrame index during file import.
Concepts Covered
index_col- Custom Index
- CSV Import
5. Python Program to Save a DataFrame as a CSV File
Problem Statement
Write a Python program to save a DataFrame into a CSV file.
Python Solution
import pandas as pd
data = {
"Name": ["Rahul", "Aman", "Priya"],
"Marks": [85, 90, 78]
}
df = pd.DataFrame(data)
df.to_csv("students_output.csv", index=False)
print("CSV file saved successfully.")
Sample Output
CSV file saved successfully.
Explanation
The to_csv() function exports a DataFrame into a CSV file. Setting index=False prevents row indexes from being written to the file.
Concepts Covered
to_csv()- CSV Export
- Data Saving
6. Python Program to Read an Excel File
Problem Statement
Write a Python program to read an Excel file using Pandas.
Python Solution
import pandas as pd
df = pd.read_excel("students.xlsx")
print(df)
Sample Output
Name Age Marks
0 Rahul 20 85
1 Aman 21 90
2 Priya 19 78
3 Sneha 22 88
Explanation
The read_excel() function imports data from an Excel file into a Pandas DataFrame.
Note: Install the openpyxl package if it is not already installed.
pip install openpyxl
Concepts Covered
read_excel()- Excel File
- Data Import
7. Python Program to Read a Specific Sheet from an Excel File
Problem Statement
Write a Python program to read a specific worksheet from an Excel file.
Python Solution
import pandas as pd
df = pd.read_excel(
"students.xlsx",
sheet_name="Sheet1"
)
print(df)
Sample Output
Name Age Marks
0 Rahul 20 85
1 Aman 21 90
2 Priya 19 78
3 Sneha 22 88
Explanation
The sheet_name parameter specifies which worksheet should be imported.
Concepts Covered
sheet_name- Excel Worksheet
read_excel()
8. Python Program to Save a DataFrame as an Excel File
Problem Statement
Write a Python program to export a DataFrame to an Excel file.
Python Solution
import pandas as pd
data = {
"Name": ["Rahul", "Aman", "Priya"],
"Marks": [85, 90, 78]
}
df = pd.DataFrame(data)
df.to_excel("students_output.xlsx", index=False)
print("Excel file saved successfully.")
Sample Output
Excel file saved successfully.
Explanation
The to_excel() function exports the DataFrame into an Excel workbook. The index=False argument prevents row indexes from being stored.
Concepts Covered
to_excel()- Excel Export
- Data Saving
9. Python Program to Read a JSON File
Problem Statement
Write a Python program to read a JSON file using Pandas.
Python Solution
import pandas as pd
df = pd.read_json("students.json")
print(df)
Sample Output
Name Age Marks
0 Rahul 20 85
1 Aman 21 90
2 Priya 19 78
3 Sneha 22 88
Explanation
The read_json() function imports structured JSON data into a DataFrame.
Concepts Covered
read_json()- JSON File
- Data Import
10. Python Program to Save a DataFrame as a JSON File
Problem Statement
Write a Python program to export a DataFrame as a JSON file.
Python Solution
import pandas as pd
data = {
"Name": ["Rahul", "Aman", "Priya"],
"Marks": [85, 90, 78]
}
df = pd.DataFrame(data)
df.to_json("students_output.json", orient="records", indent=4)
print("JSON file saved successfully.")
Sample Output
JSON file saved successfully.
Explanation
The to_json() function exports a DataFrame into JSON format. The orient="records" parameter stores each row as a JSON object, while indent=4 makes the file more readable.
Concepts Covered
to_json()- JSON Export
orient- Data Serialization
11. Python Program to Read a Text File Using Pandas
Problem Statement
Write a Python program to read a text file using Pandas.
Python Solution
import pandas as pd
df = pd.read_table("students.txt")
print(df)
Sample Output
Name Age Marks
0 Rahul 20 85
1 Aman 21 90
2 Priya 19 78
3 Sneha 22 88
Explanation
The read_table() function reads tab-separated text files and loads the data into a Pandas DataFrame.
Concepts Covered
read_table()- Text File
- Data Import
12. Python Program to Read a CSV File Without Header
Problem Statement
Write a Python program to read a CSV file that does not contain column headers.
Python Solution
import pandas as pd
df = pd.read_csv(
"students.csv",
header=None
)
print(df)
Sample Output
0 1 2
0 Rahul 20 85
1 Aman 21 90
2 Priya 19 78
3 Sneha 22 88
Explanation
Setting header=None tells Pandas that the file has no header row, so it automatically assigns numeric column labels.
Concepts Covered
header=None- CSV Import
- Column Labels
13. Python Program to Rename Columns While Reading a CSV File
Problem Statement
Write a Python program to assign custom column names while importing a CSV file.
Python Solution
import pandas as pd
columns = ["Student", "Age", "Marks"]
df = pd.read_csv(
"students.csv",
names=columns,
header=None
)
print(df)
Sample Output
Student Age Marks
0 Rahul 20 85
1 Aman 21 90
2 Priya 19 78
3 Sneha 22 88
Explanation
The names parameter assigns custom column names while importing the file.
Concepts Covered
names- Custom Column Names
- CSV Import
14. Python Program to Read Only the First Three Rows of a CSV File
Problem Statement
Write a Python program to import only the first three rows of a CSV file.
Python Solution
import pandas as pd
df = pd.read_csv(
"students.csv",
nrows=3
)
print(df)
Sample Output
Name Age Marks
0 Rahul 20 85
1 Aman 21 90
2 Priya 19 78
Explanation
The nrows parameter limits the number of rows read from the file, making it useful for previewing large datasets.
Concepts Covered
nrows- Partial Data Import
- CSV Reading
15. Python Program to Read a CSV File While Skipping Rows
Problem Statement
Write a Python program to skip the first two rows while reading a CSV file.
Python Solution
import pandas as pd
df = pd.read_csv(
"students.csv",
skiprows=2
)
print(df)
Sample Output
Aman 21 90
0 Priya 19 78
1 Sneha 22 88
Explanation
The skiprows parameter skips the specified number of rows before importing the remaining data.
Concepts Covered
skiprows- CSV Reading
- Data Import Options
16. Python Program to Check Whether a File Exists Before Reading
Problem Statement
Write a Python program to check whether a CSV file exists before reading it using Pandas.
Python Solution
import os
import pandas as pd
file_name = "students.csv"
if os.path.exists(file_name):
df = pd.read_csv(file_name)
print(df)
else:
print("File not found.")
Sample Output
Name Age Marks
0 Rahul 20 85
1 Aman 21 90
2 Priya 19 78
3 Sneha 22 88
Explanation
The os.path.exists() function checks whether the specified file exists before attempting to read it. This helps prevent runtime errors such as FileNotFoundError.
Concepts Covered
os.path.exists()- File Validation
read_csv()
17. Python Program to Save Selected Columns to a New CSV File
Problem Statement
Write a Python program to save only the Name and Marks columns from a DataFrame into a new CSV file.
Python Solution
import pandas as pd
df = pd.read_csv("students.csv")
selected_data = df[["Name", "Marks"]]
selected_data.to_csv(
"selected_students.csv",
index=False
)
print("Selected columns saved successfully.")
Sample Output
Selected columns saved successfully.
Explanation
You can select specific columns from a DataFrame and export them to a new CSV file using the to_csv() function.
Concepts Covered
- Column Selection
to_csv()- CSV Export
Chapter Summary
In this chapter, you learned how to read and write files using Pandas. You explored importing data from CSV, Excel, JSON, and text files, selecting specific columns, assigning custom indexes, exporting DataFrames to different file formats, reading files with custom options such as header, names, nrows, and skiprows, checking whether files exist before reading them, and saving selected columns into new files. These file handling techniques are essential for working with real-world datasets in data analysis projects.
Key Takeaways
read_csv()imports CSV files into a DataFrame.to_csv()exports a DataFrame to a CSV file.read_excel()andto_excel()handle Excel files.read_json()andto_json()work with JSON data.read_table()imports tab-separated text files.- Parameters like
usecols,header,names,nrows, andskiprowsprovide flexible file-reading options. os.path.exists()helps verify that a file exists before reading it.- Pandas supports reading and writing multiple file formats for efficient data analysis.
Frequently Asked Questions (FAQs)
1. Which function is used to read a CSV file in Pandas?
Use the read_csv() function.
import pandas as pd
df = pd.read_csv("students.csv")
2. How do you save a DataFrame as a CSV file?
Use the to_csv() function.
df.to_csv("output.csv", index=False)
3. Which function is used to read Excel files?
Use the read_excel() function.
df = pd.read_excel("students.xlsx")
4. How do you read only selected columns from a CSV file?
Use the usecols parameter.
df = pd.read_csv(
"students.csv",
usecols=["Name", "Marks"]
)
5. How do you import only the first few rows of a file?
Use the nrows parameter.
df = pd.read_csv(
"students.csv",
nrows=5
)
6. How do you check whether a file exists before reading it?
Use the os.path.exists() function.
import os
print(os.path.exists("students.csv"))
7. Can Pandas read JSON files?
Yes. Use the read_json() function.
df = pd.read_json("students.json")
8. Why is file handling important in Pandas?
File handling allows you to import datasets from different sources, process and analyze the data, and export the results into various formats such as CSV, Excel, and JSON. It is one of the core skills required for data analysis, business intelligence, and machine learning projects.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
