0% found this document useful (0 votes)
8 views8 pages

Python SecD

The document provides an overview of file management in Python, covering operations such as opening, reading, writing, and appending text files. It explains the use of the 'open()' function, various reading methods, and the importance of closing files. Additionally, it details the use of the csv module for reading and writing CSV and TSV files with customizable delimiters.
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)
8 views8 pages

Python SecD

The document provides an overview of file management in Python, covering operations such as opening, reading, writing, and appending text files. It explains the use of the 'open()' function, various reading methods, and the importance of closing files. Additionally, it details the use of the csv module for reading and writing CSV and TSV files with customizable delimiters.
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/ 8

Programming using Python

Course Code: DAL1003


Section D

File Management – open, close, read, write, append (on text files).

Text files: reading/writing text and numbers from/to a file; creating and reading a
formatted file (csv or tab-separated).

Online Book: https://automatetheboringstuff.com/#toc


Python - File Management - open()

File management in Python allows you to work with files such as reading, writing, appending, and modifying
them. Python provides built-in functions and methods to perform file operations easily and efficiently.

Opening Files (open() function): takes two parameters; filename or file-path, and mode.
Syntax: open(filename or file path, mode)
filename or file path: The name of the file (including its path if not in the same directory).
mode: Specifies the mode in which the file should be opened. Common modes include:
'r': Read (default mode, if not specified).
'w': Write (creates a new file or truncates (deletes previous content) an existing one).
'a': Append (adds content to the end of an existing file).
'r+': Read and write.
'b': Binary mode (e.g., 'rb' or 'wb' for reading and writing binary files).

#Example: Both statement are same, as default mode is ‘r’ or read.


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

# If the file is NOT present in the same directory as your python programming file.
file1 = open("D:\\myfiles\demofile.txt", "r")
Python - File Management - read() and close()

Reading Files: You can read a file's content using various methods:

read(): Reads the entire file content.


readline(): Reads one line at a time.
readlines(): Reads all lines into a list.

# Opening and reading a file


file = open('example.txt', 'r')
content = file.read() # Reads the entire file content
#content = file.readline() # Reads just one line
#content = file.readlines() # Reads all lines but as a list with each line as elements.
print(content)
file.close() # Important! Always close the file after utilizing it.

#OR with keyword can be used, to open and automatically close files after accessing them.

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


content = file.read()
#content = file.readline()
#content = file.readlines()
print(content) # No need to manually close the file
Python - File Management - write() and close()

Writing Files: To write to a file, you can use the write() method.
When writing, the file must be opened in 'w' (write) or 'a' (append) mode.

Note: In Write mode ('w'): If the file exists, its content will be overwritten; if it doesn't exist, a new file will be created.

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


file.write("This is a new line of text.\n")
file.write("Adding another line.")

Note: In Append mode ('a'): If the file exists, new content is added at the end. If it doesn’t exist, a new file is created.

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


file.write("\nAppending this text to the file.")

Closing Files (close() method): It's crucial to close files after you're done with them to free up system resources. You
can manually close a file using the close() method:

file = open('example.txt', 'r')


content = file.read()
file.close() # Always close the file when done
Python - File Management - csv module - Read CSV files

The csv module in Python is part of the standard library and provides tools for reading
from and writing to CSV (Comma-Separated Values) files. CSV files are widely used for
storing tabular data, and Python's csv module makes it easy to parse, manipulate, and
save such data.

Reading CSV files: Supports reading CSV files row by row, or as a dictionary with headers.
Writing CSV files: Allows you to write data to CSV files with different delimiters.
Customizing Delimiters: You can change the default comma delimiter to other characters (e.g.,
semicolons, tab-spaces).

import csv

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


reader = csv.reader(file)
for row in reader:
print(row) # Each row is a list of strings

# Changing delimiter to semicolon, instead of comma


with open('data_semicolon.csv', mode = 'r') as file:
reader = csv.reader(file, delimiter=';')
for row in reader:
print(row) # Each row is a list of strings
Python - File Management - csv module - Writing data to a CSV file

import csv

data = [
['Name', 'Age', 'Country'],
['Alice', 30, 'USA'],
['Bob', 25, 'Canada'],
['Charlie', 35, 'UK']
]

with open('output.csv', mode='w') as file:


writer = csv.writer(file)
writer.writerows(data) # Write multiple rows

with open('output_semicolon.csv', mode='w') as file:


writer = csv.writer(file, delimiter=';')
writer.writerows(data) # Writes with semicolons
Python - File Management - csv module - for Tab separated files

The csv module in Python is typically used for comma-separated values (CSV) files, but
it can be easily adapted to handle tab-separated values (TSV) files by specifying the
delimiter as a tab (\t).

import csv

# Open the TSV file


with open('data.tsv', mode='r') as file:
reader = csv.reader(file, delimiter='\t')

# Read and print each row


for row in reader:
print(row) # Each row is a list of values (strings)

# Data to be written to the TSV file


data = [ ['Name', 'Age', 'Country'],
['Alice', 30, 'USA'] ]

# Open the TSV file for writing


with open('output.tsv', mode='w') as file:
writer = csv.writer(file, delimiter='\t')
writer.writerows(data) # Write multiple rows to the file

You might also like