0% found this document useful (0 votes)
2 views35 pages

Python Programming_File Handling

The document provides an overview of file handling in Python, including concepts such as current working directory, absolute and relative paths, and methods for creating, removing, and manipulating directories and files. It explains how to read from and write to files using different modes, as well as the use of the OS and shutil modules for file operations. Key functions like os.mkdir(), os.rmdir(), and shutil.copy() are highlighted for practical file management tasks.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
2 views35 pages

Python Programming_File Handling

The document provides an overview of file handling in Python, including concepts such as current working directory, absolute and relative paths, and methods for creating, removing, and manipulating directories and files. It explains how to read from and write to files using different modes, as well as the use of the OS and shutil modules for file operations. Key functions like os.mkdir(), os.rmdir(), and shutil.copy() are highlighted for practical file management tasks.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 35

File Handling

The Current Working Directory


Every program that runs on your computer has a current working directory, or cwd.
Any filenames or paths that do not begin with the root folder are assumed to be under
the current working directory.

To get the CWD as string value

To change the CWD.


Absolute and Relative file paths
File Systems
Your computer drive is organized in a hierarchical structure of files and directories.
Files -- These contain information. Examples: text files, drawing files, python files, etc.
Directories -- These contain files and directories inside of them.

An absolute file path describes how to access a given file or directory, starting from the
root of the file system. A file path is also called a pathname.

A relative file path is relative to the program’s current working directory. If you use a
relative file path from the wrong directory, then the path will refer to a different file than
you intend, or it will refer to no file at all.
Example:
Accessing Absolute and Real Paths
An absolute path helps you find the full path of a file or directory relative to the
current working directory.

import os
os.path.abspath("src/examplefile.txt")

Output
/Users/dannysteenman/home/projects/example-project/src/examplefile.txt
Creating a Directory
We can create a new directory using the os.mkdir() function, as shown below.

import os

os.mkdir("C:\PythonProject")

By default, if you don't specify the whole path in the mkdir() function, it will create
the specified directory in the current working directory or drive.

os.makedirs() method in Python is used to create a directory recursively. That


means while making leaf directory if any intermediate-level directory is missing,
os.makedirs() method will create them all.

import os

os.makedirs(“C:\PythonProject\OSModule\UBDTCE")
Removing a Directory
The rmdir() function in the OS module removes the specified directory either
with an absolute or relative path.
Note that, for a directory to be removed, it should be empty.

import os

os.rmdir("C:\\PythonProject")
os.path.join method
The os.path.join() method merges components in a pathname to create a full
pathname. It automatically adds forward slashes (“/”) into the pathname when
needed.

import os
path = "/Home"
combined_path = os.path.join(path, "tutorials", "main_file.py")
print(combined_path)

/Home/tutorials/main_file.py
import os
cwd = os.getcwd()
app = os.path.join(cwd, "app.py")
print(app)

/Users/krunal/Desktop/code/pyt/database/app.py
Reading and Writing Files

Before performing any operation on the file like reading or writing, first, we have to open
that file. For this, we should use Python’s inbuilt function open() but at the time of opening,
we have to specify the mode, which represents the purpose of the opening file.
f = open(filename, mode)
Where the following mode is supported:
. r: open an existing file for a read operation.
. w: open an existing file for a write operation. If the file already contains some data then
it will be overridden but if the file is not present then it creates the file as well.
. a: open an existing file for append operation. It won’t override existing data.
. r+: To read and write data into the file. The previous data in the file will be overridden.
. w+: To write and read data. It will override existing data.
. a+: To append and read data from the file. It won’t override existing data.
file=open("1a.txt","w+")
file.write("Hello everyone!")
file.close()

This will open the text file named 1a.txt(which is present in the working directory) in
write mode.
If the file does not exist, it will be created.
This method will erase all the data which was present earlier in the text file.
file=open("1a.txt","a")
file.write("\nWelcome to the class on Python Programming")
file.close()

This will open the text file named 1a.txt(which is present in the working directory) in
append mode.
If the file does not exist, it will be created.
This method will add the data in addition to the existing data in the text file.
file=open("1a.txt","w")
lines=["Good Morning!"," Had your breakfast."," Switch on the computer"]
file.writelines(lines)
file.close()

This will open the text file named 1a.txt(which is present in the working directory) in
write mode.
If the file does not exist, it will be created.
This method will add multiple lines to the existing data in the text file.
This will open the text file named 1a.txt(which is present in the working directory) in
read mode. It reads all the content of the text file.
If file.read(10) is passed, it will read only 10 characters of the text file.
file.readline() reads a single line from the file.
file.readlines() reads all the lines of the file.
Text files are first opened and then the content is accessed from it in the order of lines. By
default, the line numbers begin with the 0 th index.

A file object can be created in Python and then readlines() method can be invoked on this
object to read lines into a stream.

It initially reads the entire content of the file and keep a copy of it in memory. The lines at
the specified indices are then accessed.

# open the sample file used


file = open('test.txt')

# read the content of the file opened


content = file.readlines()

# read 10th line from the file


print(“third line")
print(content[2])

# print first 3 lines of file


print("first three lines")
print(content[0:3])
with open(r"myfile.txt", 'r') as fp:
lines = len(fp.readlines())
print('Total Number of lines:', lines)
# Demonstrated Python Program
# to read file character by character
file = open('file.txt', 'r')
while 1:
# read by character
char = file.read(1)
if not char:
break
print(char)
file.close()
Organizing Files
What is OS module?
This module helps interact with the operating system and provides a way of
using os dependent functionalities. It has many functions such startfile(),
getcwd() and many more. In this article, we will use the listdr() and the path.
isfile() functions.

What is shutil module?


This module offers a number of high-level operations on files and collection of
files. Using it, we can move, copy and rename our files. It has many useful
functions such as copyfile(), copymode(), etc.
shutil.copy(source, destination)

shutil.move(source, destination)
os.unlink(path) will delete the file at path.
os.rmdir(path) will delete the folder at path.
shutil.rmtree(path) will remove the folder at path, and all files and folders
it contains will also be deleted.
To delete all .rxt files

You might also like