Python Programming_File Handling
Python Programming_File Handling
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.
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.
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