0% found this document useful (0 votes)
14 views28 pages

File Management2

File management in Python involves handling text and binary files through various operations such as opening, reading, writing, and closing files using the `open()` function and file object methods. Python supports multiple file access modes, including read, write, and append, and provides built-in functions for efficient file handling. While file management offers versatility and cross-platform compatibility, it also presents challenges such as error-proneness and security risks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views28 pages

File Management2

File management in Python involves handling text and binary files through various operations such as opening, reading, writing, and closing files using the `open()` function and file object methods. Python supports multiple file access modes, including read, write, and append, and provides built-in functions for efficient file handling. While file management offers versatility and cross-platform compatibility, it also presents challenges such as error-proneness and security risks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

File Management

File management in Python is a crucial aspect of working with text files and other types of
data. Python treats files differently as text or binary and this is important. Each line of code
includes a sequence of characters and they form a text file. Each line of a file is terminated with
a special character, called the EOL or End of Line characters like comma {,} or newline
character. It ends the current line and tells the interpreter a new one has begun.Text files are
commonly used for tasks like reading and writing configuration files, logs, data storage, and more.
Python provides several built-in modes for file management, making it easy to work with text files.
Python provides inbuilt functions for creating, writing, and reading files. There are two types of
files that can be handled in python, normal text files and binary files (written in binary language,
0s, and 1s).
 Text files: In this type of file, Each line of text is terminated with a special character called
EOL (End of Line), which is the new line character (‘\n’) in python by default.
 Binary files: In this type of file, there is no terminator for a line, and the data is stored after
converting it into machine-understandable binary language.

File Access Modes


Access modes govern the type of operations possible in the opened file. It refers to how the file
will be used once its opened. These modes also define the location of the File Handle in the file.
File handle is like a cursor, which defines from where the data has to be read or written in the
file. There are 6 access modes in python.
1. Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning of the
file. If the file does not exists, raises the I/O error. This is also the default mode in which a
file is opened.
2. Read and Write (‘r+’): Open the file for reading and writing. The handle is positioned at
the beginning of the file. Raises I/O error if the file does not exist.
3. Write Only (‘w’) : Open the file for writing. For the existing files, the data is truncated and
over-written. The handle is positioned at the beginning of the file. Creates the file if the file
does not exist.
4. Write and Read (‘w+’) : Open the file for reading and writing. For an existing file, data is
truncated and over-written. The handle is positioned at the beginning of the file.
5. Append Only (‘a’): Open the file for writing. The file is created if it does not exist. The
handle is positioned at the end of the file. The data being written will be inserted at the end,
after the existing data.
6. Append and Read (‘a+’) : Open the file for reading and writing. The file is created if it does
not exist. The handle is positioned at the end of the file. The data being written will be
inserted at the end, after the existing data.

Let's explore the process of working with text files in Python in detail.

1. Opening a Text File: The Python open() function is used to open internally stored files. To
work with a text file, you must first open it. You can use the `open()` function for this purpose. It
takes two arguments: the file path and the mode in which you want to open the file. The modes
can be:

- `'r'`: Read. It is passed as default if no parameter is supplied and returns an error if no such
file exists.

- `'w'`: Write (creates a new file or overwrites an existing one).

- `'a'`: Append (appends data to an existing file).

- `'x'`: Exclusive creation (creates a new file but raises an error if the file already exists).

- `'b'`: Binary mode (to work with binary files).

Syntax:-
open(file_name, mode)
Parameters:-
file_name: This parameter as the name suggests, is the name of the file that we want to open.
mode: This parameter is a string that is used to specify the mode in which the file is to be opened.

How to open a file in Python?


In Python, we can open a file by using the open() function already provided to us by Python. By
using the open() function, we can open a file in the current directory as well as a file located in
a specified location with the help of its path. In this example, we are opening a file “gfg.txt”
located in the current directory and “gfg1.txt” located in a specified location.
Code example
# opens gfg text file of the current directory

f = open("gfg.txt")

# specifying the full path

f = open("C:/HP/Desktop/gfg1.txt")

Examples of the Python open() function

Creating a Text File


The open() function in Python can be used to create a file. Here we will be creating a text file
named “geeksforgeeks.txt”.

Example:

created_file = open("geeksforgeeks.txt","x")

# Check the file

print(open("geeksforgeeks.txt","r").read() == False)

Output:
False

Reading and Writing the file


Here we will write the following string to the “geeksforgeeks.txt” file that we just created and
read the same file again.
Example:-
my_file = open("geeksforgeeks.txt", "w")

my_file.write("Geeksforgeeks is best for DSA")

my_file.close()

#let's read the contents of the file now

my_file = open("geeksforgeeks.txt","r")

print(my_file.read())

Output:
Geeksforgeeks is best for DSA

Appending content to the file


Here we will append the following text to the “geeksforgeeks.txt” file and again read the same.
For Example:-

my_file = open("geeksforgeeks.txt","a")

my_file.write("..>>Visit geeksforgeeks.org for more!!<<..")

my_file.close()

# reading the file

my_file = open("geeksforgeeks.txt","r")

print(my_file.read())

Output:

Geeksforgeeks is best for DSA..>>Visit geeksforgeeks.org for more!!<<..

The difference between “w” and “a” is that one overrides over the existing content whereas the
latter adds content to the existing file keeping the content intact.
2. Reading from a Text File:

To read data from a text file, you can use various methods provided by the file object, such as
`read()`, `readline()`, or `readlines()`.

- `read()`: Reads the entire file content as a single string. Reads n bytes, if no n specified, reads
the entire file.

Syntax:- File_object.read([n])

- `readline()`: Reads one line at a time. However, does not reads more than one line, even if n
exceeds the length of the line.
Syntax:- File_object.readline([n])

- `readlines()`: Reads all lines into a list.

Syntax:- File_object.readlines()

Example:

# Program to show various ways to read and

# write data in a file.

file1 = open("myfile.txt","w")

L = ["This is Delhi \n","This is Paris \n","This is London \n"]

# \n is placed to indicate EOL (End of Line)

file1.write("Hello \n")

file1.writelines(L)

file1.close() #to change file access modes

file1 = open("myfile.txt","r+")

print("Output of Read function is ")

print(file1.read())
print()

# seek(n) takes the file handle to the nth

# byte from the beginning.

file1.seek(0)

print( "Output of Readline function is ")

print(file1.readline())

print()

file1.seek(0)

# To show difference between read and readline

print("Output of Read(9) function is ")

print(file1.read(9))

print()

file1.seek(0)

print("Output of Readline(9) function is ")

print(file1.readline(9))

file1.seek(0)

# readlines function

print("Output of Readlines function is ")

print(file1.readlines())

print()

file1.close()
Output:
Output of Read function is
Hello
This is Delhi
This is Paris
This is London

Output of Readline function is


Hello

Output of Read(9) function is


Hello
Th

Output of Readline(9) function is


Hello

Output of Readlines function is


['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London
\n']

Appending to a file

# Python program to illustrate

# Append vs write mode

file1 = open("myfile.txt","w")

L = ["This is Delhi \n","This is Paris \n","This is London \n"]

file1.writelines(L)

file1.close()

# Append-adds at last

file1 = open("myfile.txt","a")#append mode

file1.write("Today \n")
file1.close()

file1 = open("myfile.txt","r")

print("Output of Readlines after appending")

print(file1.readlines())

print()

file1.close()

# Write-Overwrites

file1 = open("myfile.txt","w")#write mode

file1.write("Tomorrow \n")

file1.close()

file1 = open("myfile.txt","r")

print("Output of Readlines after writing")

print(file1.readlines())

print()

file1.close()

Output:
Output of Readlines after appending
['This is Delhi \n', 'This is Paris \n', 'This is London \n', 'Today
\n']

Output of Readlines after writing


['Tomorrow \n']
3. Writing to a Text File: To write data to a text file, you can use the `write()` method for
individual lines.

Syntax:- File_object.write(str1)

or the `writelines()` method for a list of lines.

Syntax:- File_object.writelines(L) for L = [str1, str2, str3]

You should open the file in write ('w') or append ('a') mode to perform write operations.

Example:-

# Python program to demonstrate

# writing to file

# Opening a file

file1 = open('myfile.txt', 'w')

L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]

s = "Hello\n"

# Writing a string to file

file1.write(s)

# Writing multiple strings

# at a time

file1.writelines(L)

# Closing file
file1.close()

# Checking if the data is

# written to file or not

file1 = open('myfile.txt', 'r')

print(file1.read())

file1.close()

Output:
Hello
This is Delhi
This is Paris
This is London

Appending to a file:- When the file is opened in append mode, the handle is positioned at the
end of the file. The data being written will be inserted at the end, after the existing data. Let’s
see the below example to clarify the difference between write mode and append mode.

# Python program to illustrate


# Append vs write mode
file1 = open("myfile.txt", "w")
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
file1.writelines(L)
file1.close()

# Append-adds at last
file1 = open("myfile.txt", "a") # append mode
file1.write("Today \n")
file1.close()
file1 = open("myfile.txt", "r")
print("Output of Readlines after appending")
print(file1.read())
print()
file1.close()

# Write-Overwrites
file1 = open("myfile.txt", "w") # write mode
file1.write("Tomorrow \n")
file1.close()

file1 = open("myfile.txt", "r")


print("Output of Readlines after writing")
print(file1.read())
print()
file1.close()

Output:
Output of Readlines after appending
This is Delhi
This is Paris
This is London
Today

Output of Readlines after writing


Tomorrow
4. Closing a File:

It's essential to close the file explicitly when you're done with it. close() function closes the file
and frees the memory space acquired by that file. It is used at the time when the file is no longer
needed or if it is to be opened in a different file mode. Syntax:- File_object.close()

# Opening and Closing a file "MyFile.txt"

# for object name file1.

file1 = open("MyFile.txt","a")

file1.close()

In summary, file management in Python involves opening, reading, writing, and closing text files
using the `open()` function and various file object methods.

Advantages of File Handling


 Versatility: File handling in Python allows you to perform a wide range of operations, such
as creating, reading, writing, appending, renaming, and deleting files.
 Flexibility: File handling in Python is highly flexible, as it allows you to work with different
file types (e.g. text files, binary files, CSV files, etc.), and to perform different operations on
files (e.g. read, write, append, etc.).
 User–friendly: Python provides a user-friendly interface for file handling, making it easy to
create, read, and manipulate files.
 Cross-platform: Python file-handling functions work across different platforms (e.g.
Windows, Mac, Linux), allowing for seamless integration and compatibility.

Disadvantages of File Handling


 Error-prone: File handling operations in Python can be prone to errors, especially if the
code is not carefully written or if there are issues with the file system (e.g. file permissions,
file locks, etc.).
 Security risks: File handling in Python can also pose security risks, especially if the program
accepts user input that can be used to access or modify sensitive files on the system.
 Complexity: File handling in Python can be complex, especially when working with more
advanced file formats or operations. Careful attention must be paid to the code to ensure that
files are handled properly and securely.
 Performance: File handling operations in Python can be slower than other programming
languages, especially when dealing with large files or performing complex operations.

With statement
with statement in Python is used in exception handling to make the code cleaner and much more
readable. It simplifies the management of common resources like file streams. Unlike the above
implementations, there is no need to call file.close() when using with statement. The with
statement itself ensures proper acquisition and release of resources.

Syntax: with open filename as file:

# Program to show various ways to

# write data to a file using with statement

L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]

# Writing to file

with open("myfile.txt", "w") as file1:

# Writing data to a file

file1.write("Hello \n")

file1.writelines(L)
# Reading from file

with open("myfile.txt", "r+") as file1:

# Reading form a file

print(file1.read())

Output:
Hello
This is Delhi
This is Paris
This is London

using for statement:


To write to a file in Python using a for statement, you can follow these steps:

Open the file using the open() function with the appropriate mode (‘w’ for writing).
Use the for statement to loop over the data you want to write to the file.
Use the file object’s write() method to write the data to the file.
Close the file using the file object’s close() method.

# Open the file for writing

with open('file.txt', 'w') as f:

# Define the data to be written

data = ['This is the first line', 'This is the second line', 'This is the third line']

# Use a for loop to write each line of data to the file

for line in data:

f.write(line + '\n')
# Optionally, print the data as it is written to the file

print(line)

# The file is automatically closed when the 'with' block ends

Output
This is the first line
This is the second line
This is the third line
In this example, the file is opened for writing using the with open(‘file.txt’, ‘w’) as f statement.
The data to be written is stored in a list called data. The for statement is used to loop over each
line of data in the list. The f.write(line + ‘\n’) statement writes each line of data to the file with
a newline character (\n) at the end. Finally, the file is automatically closed when the with block
ends.

The code opens a file called file.txt in write mode using a with block to ensure the file is properly
closed when the block ends. It defines a list of strings called data that represents the lines to be
written to the file. The code then uses a for loop to iterate through each string in data, and writes
each string to the file using the write() method. The code appends a newline character to each
string to ensure that each string is written on a new line in the file. The code optionally prints
each string as it is written to the file.
With Statement

In Python, the `with` statement is used to simplify the management of resources, such as file
handling or database connections. It ensures that the resource is properly acquired and released
when you're done with it. The `with` statement is often used in combination with context
managers, which define methods to allocate and release resources.

One of the most common use cases for the `with` statement is working with files, where you
open a file, perform some operations, and then automatically close the file when you exit the
`with` block. This helps in preventing resource leaks and makes your code more concise and
readable.

Here's an example to illustrate the use of the `with` statement with a file:

# Opening a file using with statement

with open('example.txt', 'w') as file:

file.write('Hello, World!')

# File is automatically closed when the block is exited

In this example:

1. We use the `with` statement to open the file 'example.txt' in write mode (`'w'`).

2. Inside the `with` block, we write the string 'Hello, World!' to the file.

3. As soon as the code block inside the `with` statement is completed, the file is automatically
closed. You don't need to explicitly call `file.close()`.

Reading and Writing numbers from/to file

Reading and writing numbers from/to a file in Python involves several steps. You can use the
`open()` function to create or open a file, and then use file objects to read and write numeric
data. Here's a detailed explanation of how to read and write numbers to/from a file in Python:
### Writing Numbers to a File:

To write numbers to a file, you need to:

1. Open the file for writing:

Use the `open()` function to open a file in write mode ('w' or 'wb' for binary files). For example:

with open('numbers.txt', 'w') as file:

Replace 'numbers.txt' with the name of the file you want to create or write to.

2. Write numbers to the file:

You can use the `write()` method of the file object to write numbers as text to the file. For
example:

numbers = [1, 2, 3, 4, 5]

for number in numbers:

file.write(str(number) + '\n')

This code will write each number followed by a newline character ('\n') to separate them in the
file.

3. Close the file:

Always close the file when you're done writing to it. The `with` statement will automatically
handle the closing for you when it goes out of scope.
Reading Numbers from a File:

To read numbers from a file, you need to:

1. Open the file for reading:

Use the `open()` function to open a file in read mode ('r' or 'rb' for binary files). For example:

with open('numbers.txt', 'r') as file:

Make sure you use the same file name you used for writing.

2. Read numbers from the file:

You can use the `read()`, `readline()`, or `readlines()` methods to read the numbers. For
example:

numbers = []

for line in file:

numbers.append(int(line.strip()))

This code reads each line, converts it to an integer using `int()`, and appends it to a list. The
`strip()` method removes any leading or trailing whitespace, including the newline character.

3. Close the file:

As always, close the file when you're done reading it. The `with` statement will handle the
closing for you.
Here's a complete example that demonstrates writing numbers to a file and then reading them:

# Writing numbers to a file

numbers_to_write = [1, 2, 3, 4, 5]

with open('numbers.txt', 'w') as file:

for number in numbers_to_write:

file.write(str(number) + '\n')

# Reading numbers from the same file

numbers_to_read = []

with open('numbers.txt', 'r') as file:

for line in file:

numbers_to_read.append(int(line.strip()))

print("Numbers written:", numbers_to_write)

print("Numbers read:", numbers_to_read)

This example writes a list of numbers to a file and then reads and prints them. The output will
show that the numbers were successfully written and read:

Output

Numbers written: [1, 2, 3, 4, 5]

Numbers read: [1, 2, 3, 4, 5]


Certainly! Let's break down the provided Python program that writes numbers to a file and then
reads and prints them. Here's a detailed explanation of each part:

# Writing numbers to a file

numbers_to_write = [1, 2, 3, 4, 5]

with open('numbers.txt', 'w') as file:

for number in numbers_to_write:

file.write(str(number) + '\n')

1. Writing Numbers to a File:

- We start by defining a list called `numbers_to_write` containing a series of numbers `[1, 2,


3, 4, 5]`.

- We then use the `open()` function to open a file named 'numbers.txt' in write mode (`'w'`).
This creates or opens the file for writing. The `with` statement is used to ensure the file is
automatically closed when we're done.

- Inside the `with` block, we loop through the `numbers_to_write` list, converting each number
to a string using `str(number)`, and then writing it to the file. We append `'\n'` (a newline
character) after each number to separate them in the file.
# Reading numbers from the same file

numbers_to_read = []

with open('numbers.txt', 'r') as file:

for line in file:

numbers_to_read.append(int(line.strip()))

2. Reading Numbers from the Same File:

- We continue by defining an empty list called `numbers_to_read`. This list will store the
numbers we read from the file.

- Using the `open()` function again, we open the 'numbers.txt' file, but this time in read mode
(`'r'`) to read the numbers. We use the `with` statement to ensure the file is properly closed after
reading.

- Inside the `with` block, we iterate over each line in the file using a `for` loop. Each line
corresponds to one of the numbers we previously wrote.

- For each line, we call `int(line.strip())` to convert the string back to an integer. The `strip()`
method is used to remove any leading or trailing whitespace, including the newline character
('\n'). We then append the resulting integer to the `numbers_to_read` list.

print("Numbers written:", numbers_to_write)

print("Numbers read:", numbers_to_read)


3. Printing the Results:

- Finally, we print the contents of the `numbers_to_write` and `numbers_to_read` lists to verify
that the numbers were successfully written to the file and then read and stored in the program.

Output:

Numbers written: [1, 2, 3, 4, 5]

Numbers read: [1, 2, 3, 4, 5]

This output confirms that the program correctly wrote the numbers to the file and successfully
read and stored them back in the `numbers_to_read` list. This demonstrates the process of writing
and reading numbers to/from a file in Python.

Creating and Reading a Formatted File(CSV)

A CSV (Comma Separated Values) file is a form of plain text document which uses a
particular format to organize tabular information. CSV file format is a bounded text document
that uses a comma to distinguish the values. Every row in the document is a data log. Each log
is composed of one or more fields, divided by commas. It is the most popular file format for
importing and exporting spreadsheets and databases.

Reading a CSV File


There are various ways to read a CSV file that uses either the CSV module or the pandas library.

 csv Module: The CSV module is one of the modules in Python which provides classes for
reading and writing tabular information in CSV file format.
 pandas Library: The pandas library is one of the open-source Python libraries that provide
high-performance, convenient data structures and data analysis tools and techniques for
Python programming.
Using csv.reader(): At first, CSV file is opened using the open() method in ‘r’ mode(specifies
read mode while opening a file) which returns the file object then it is read by using the reader()
method of CSV module that returns the reader object that iterates throughout the lines in the
specified CSV document. For example:-

import csv

# opening the CSV file

with open('Giants.csv', mode ='r')as file:

# reading the CSV file

csvFile = csv.reader(file)

# displaying the contents of the CSV file

for lines in csvFile:

print(lines)

Output:
['Organization', 'CEO', 'Established']

['Alphabet', 'Sundar Pichai', '02-Oct-15']

['Microsoft', 'Satya Nadella', '04-Apr-75']

['Amazon', 'Jeff Bezos', '05-Jul-94']

In the above program reader() method is used to read the Giants.csv file which maps the data
into lists.
Example 2

import csv
with open('chocolate.csv') as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
print(row)

Output

['Company', 'Bean Origin or Bar Name', 'REF', 'Review Date', 'Cocoa Percent',
'Company Location', 'Rating', 'Bean Type', 'Country of Origin']
['A. Morin', 'Agua Grande', '1876', '2016', '63%', 'France', '3.75', 'Â\xa0', 'Sao
Tome']
['A. Morin', 'Kpime', '1676', '2015', '70%', 'France', '2.75', 'Â\xa0', 'Togo']
['A. Morin', 'Atsane', '1676', '2015', '70%', 'France', '3', 'Â\xa0', 'Togo']
['A. Morin', 'Akata', '1680', '2015', '70%', 'France', '3.5', 'Â\xa0', 'Togo']
['Acalli', 'Chulucanas, El Platanal', '1462', '2015', '70%', 'U.S.A.', '3.75',
'Â\xa0', 'Peru']
['Acalli', 'Tumbes, Norandino', '1470', '2015', '70%', 'U.S.A.', '3.75', 'Criollo',
'Peru']
['Adi', 'Vanua Levu', '705', '2011', '60%', 'Fiji', '2.75', 'Trinitario', 'Fiji']
['Adi', 'Vanua Levu, Toto-A', '705', '2011', '80%', 'Fiji', '3.25', 'Trinitario',
'Fiji']
['Adi', 'Vanua Levu', '705', '2011', '88%', 'Fiji', '3.5', 'Trinitario', 'Fiji']
['Adi', 'Vanua Levu, Ami-Ami-CA', '705', '2011', '72%', 'Fiji', '3.5', 'Trinitario',
'Fiji']
['Aequare (Gianduja)', 'Los Rios, Quevedo, Arriba', '370', '2009', '55%', 'Ecuador',
'2.75', 'Forastero (Arriba)', 'Ecuador']
['Aequare (Gianduja)', 'Los Rios, Quevedo, Arriba', '370', '2009', '70%', 'Ecuador',
'3', 'Forastero (Arriba)', 'Ecuador']
['Ah Cacao', 'Tabasco', '316', '2009', '70%', 'Mexico', '3', 'Criollo', 'Mexico']

Each row of the CSV file forms a list wherein every item can be easily accessed, as follows:
import csv
with open('chocolate.csv') as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
print("The {} company is located in {}.".format(row[0], row[5]))

Output

The Company company is located in Company Location.


The A. Morin company is located in France.
The A. Morin company is located in France.
The A. Morin company is located in France.
The A. Morin company is located in France.
The Acalli company is located in U.S.A..
The Acalli company is located in U.S.A..
The Adi company is located in Fiji.
The Adi company is located in Fiji.
The Adi company is located in Fiji.
The Adi company is located in Fiji.

 Using pandas.read_csv() method: It is very easy and simple to read a CSV file using pandas
library functions. Here read_csv() method of pandas library is used to read data from CSV
files. For example:-

import pandas

# reading the CSV file

csvFile = pandas.read_csv('Giants.csv')

# displaying the contents of the CSV file

print(csvFile)
Output:
Organization CEO Established

0 Alphabet Sundar Pichai 02-Oct-15

1 Microsoft Satya Nadella 04-Apr-75

2 Amazon Jeff Bezos 05-Jul-94

In the above program, the csv_read() method of pandas library reads the Giants.csv file and maps
its data into a 2D list.

##########################################################################

Creating formatted files, such as CSV (Comma-Separated Values) files, in Python can be
accomplished using various libraries, with the most commonly used library being the built-in `csv`
module. This module simplifies the process of working with CSV files by providing functions and
classes for reading and writing CSV data. Here's a detailed explanation of how to create CSV files
in Python:

## Creating a CSV File

To create a CSV file in Python, you'll need to follow these steps:

1. Import the `csv` module: First, you need to import the `csv` module to work with CSV files.

2. Open the CSV file for writing: Use the `open()` function to create a CSV file and open it in write
mode. You can specify the file name, the mode (`'w'` for write), and other optional parameters like
newline settings.

with open('data.csv', 'w', newline='') as csvfile:

The `newline=''` argument is important to ensure cross-platform compatibility for line endings
(e.g., Windows uses '\r\n', Unix-like systems use '\n').
3. Create a `csv.writer` object: Next, create a `csv.writer` object that allows you to write data to
the CSV file. Pass the `csvfile` object you created in the previous step to the `csv.writer`
constructor.

csv_writer = csv.writer(csvfile)

4. Write data to the CSV file: You can write rows of data to the CSV file using the `writerow()`
method of the `csv.writer` object. Data should be provided as a list of values. Each list represents
a row in the CSV file.

data = [['Name', 'Age', 'City'],

['Alice', 30, 'New York'],

['Bob', 25, 'Los Angeles']]

for row in data:

csv_writer.writerow(row)

5. Close the CSV file: After writing all the data, it's essential to close the CSV file to ensure that
changes are saved properly.

csvfile.close()

Your CSV file 'data.csv' now contains the data you specified in the `data` list.

Example that demonstrates creating and reading a CSV file in Python:


# Creating a CSV file

with open('example.csv', 'w', newline='') as csvfile:

writer = csv.writer(csvfile)

writer.writerow(['Name', 'Age', 'City'])

writer.writerow(['Alice', 25, 'New York'])

writer.writerow(['Bob', 30, 'San Francisco'])


# Reading a CSV file

with open('example.csv', 'r') as csvfile:

reader = csv.reader(csvfile)

for row in reader:

print(row)

The output of the program I provided will be as follows:

['Name', 'Age', 'City']

['Alice', '25', 'New York']

['Bob', '30', 'San Francisco']

The program first creates a CSV file named 'example.csv' and writes three rows to it. Then, it reads
the contents of the same file and prints each row as a list of values.

You might also like