Working with Files in Python:
Python uses file objects to interact with external files on our computer. These file objects can be any sort of file we have on our computer, whether it be an audio file, a text file, emails, Excel documents, etc.
File Path:
# get the path of current working directory :
pwd
# using os module :
import os
os.getcwd()
# Relative path of a directory :
import os
os.path.relpath(path, [start])
# Example : set the path of current project.
proj_main_dir= os.path.relpath("C:\\ProjectFile\\path")
Listing Files in a directory :
# list all the files and folder of current directory :
os.listdir()
# list all the files and folder of given path :
os.listdir("path\\to\\the\\directory")
Open a File in Python:
Python uses open() function to open a file. it takes two parameter; filename and mode .
- There are four modes to open a file:
- "r" - Read - Default Value- Opens a file for reading. Will throw an error incase file is not present.
- "a" - Append - Opens a file for appending, It will creates the file if it does not exist
- "w" - Write - Opens a file for writing, It will creates the file if it does not exist
- "x' - Create - Creates the specified file, throw an error if the file exists
- We can also specify whether the file should be open as binary or text mode.
- "t" - Text - Default value. Text mode
- "b" - Binary - Binary mode (e.g. images)
my_file = open("C:\\path\\of\\the\\file.txt", "r")
my_file = open("C:\\path\\of\\the\\file.txt", "rt")
Reading a File in Python:
- using read() method:
my_file.read() my_file.seek(0) # After using read() the "cursor" will be at the end of file. To reset it use seek().
- using readlines() method:
my_file.readlines()
Closing a File in Python:
We should always close our files after working on it. in some cases, due to buffering, changes made to a file may not show until we close the file.
my_file = open("C:\\path\\of\\the\\file.txt", "r")
print(my_file.readline())
f.close()
Writing to a file in Python:
- using "a" - append mode:
my_file = open("C:\\path\\of\\the\\file.txt", "a") my_file.write("Write something interesting") my_file.close()
- using "w" - Write mode. It will override the entire file if it exist. Or Create a new file if it does not exist :
my_file = open("C:\\path\\of\\the\\file.txt", "w") my_file.write("Write something interesting again.") my_file.close()
- using "x" - Create mode.
my_file = open("C:\\path\\of\\the\\file.txt", "x") my_file.write("Write something interesting again.") my_file.close()
Moving a file in Python:
We can use shutil module to move the files from one location to another. However we need to keep in mind that we need to have the proper permission.
# Syntax :
import shutil
shutil.move(source, destination, copy_function)
# Example :
shutil.move("C:\\path\\of\\source\\file.extension", "C:\\path\\to\\destination\\Folder\\")
shutil.move("C:\\path\\of\\source\\file.extension", proj_main_dir+"\\Folder\\")
Delete a file in Python:
- using "os.remove()" - function. we must import the OS module before using it.
import os os.remove("my_file")
Delete a file / folder in Python:
- "os.rmdir(path)" it deletes a folder (folder must be empty) at the path we provide.
- "os.unlink(path)" it deletes a file at the path we provide.
- "shutil.rmtree(path)" it deletes all files and folders at the path we provide.
import os
os.rmdir("my_directory")
Check if file exist in Python:
- using "os.path.exist()" - function. we might want to check if the file exists before we try to delete it or create a new file.
import os if os.path.exist("my_file"): os.remove("my_file") else: print("The file does not exist")
Iterating through a file in Python:
- using for loop.
for line in open('test.txt'): print(line)
- We could have called the "line" object anything.
- By not calling .read() on the file, the whole text file is not stored in memory.
Walking through a directory :
for folder , sub_folders , files in os.walk("folder_Name"):
print("Currently at folder: "+ folder)
print("THE SUBFOLDERS ARE: ")
for sub_fold in sub_folders:
print("\t Subfolder: "+sub_fold )
print("THE FILES ARE: ")
for f in files:
print("\t File: "+f)
print('\n')