Python Tutorials
- Python
- How to install Python?
- PIP
- How to Run Python Program
- Python Identifiers,Statement, Indentation and Comments
- Variable
- Data type
- Decision Making
- Python Loops
- Break,Continue, Pass
- Functions
- Predefine Functions
- Lambda Functions
- Variable Scope
- List
- Tuple
- Python Sets
- Python Dictionary
- Python String
- String Formating
- Input/Output
- File Handling (Input / Output)
- Iterators
- Python Modules
- Python Date
- Python JSON
- Classes and Objects
- Constructor
- Polymorphism
- Encapsulation
- inheritance
- Class or Static Variables in Python
- class method vs static method
- Abstraction
- Exception Handling
- MySql Python
- MySql Create Database
- MySql CRUD
- Django
What is File Handling in python?
Files are named locations on disk to store related information. They are used to permanently store data in a non-volatile memory.
When we want to read from or write to a file, we need to open it first.
File name : index.py
a file operation can be done in the following order.
Open a file
Read or write - Performing operation
Close the file
Opening Files in Python
Python has a built-in open() function to open a file. This function returns a file object.
open() function that accepts two arguments, file name and access mode in which the file is accessed. The function returns a file object which can be used to perform various operations like reading, writing, etc.
File name : index.py
file object = open(<file-name>, <access-mode>, <buffering>)
File name : index.py
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
"t" - Text - Default value. Text mode
"b" - Binary - Binary mode (e.g. images)
"+" - Opens a file for updating (reading and writing)
How to open file
File name : index.py
f = open("sana.txt")
Example
Here "r" for read, and "t" for text are the default values, you do not need to specify them.
File name : index.py
f = open("sana.txt", "rt")
File
File name : sana.txt
This file is for testing purposes.
Good Luck!
Example
File name : index.py
f = open("demofile.txt", "r")
print(f.read())
If the file is located in a different location, you will have to specify the file path.
File name : index.py
f = open("D:\\myfiles\sana.txt", "r")
print(f.read())
Read Only Parts of the File
By default the read() method returns the whole text, but you can also specify how many characters you want to return:
File name : index.py
f = open("sana.txt", "r")
print(f.read(5))
Return the 5 first characters of the file:
Read Lines
You can return one line by using the readline() method:
File name : index.py
f = open("sana.txt", "r")
print(f.readline())
ead the whole file, line by line
File name : index.py
f = open("demofile.txt", "r")
for x in f:
print(x)
Close Files
It is a good practice to always close the file when you are done with it.
File name : index.py
f = open("demofile.txt", "r")
print(f.readline())
f.close()
Write to an Existing File
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content
File name : index.py
f = open("sana.txt", "a")
f.write("Now the file has more content!")
f.close()
#open and read the file after the appending:
f = open("sana.txt", "r")
print(f.read())
Override File
File name : index.py
f = open("sana.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
#open and read the file after the appending:
f = open("sana.txt", "r")
print(f.read())
Delete a File
To delete a file, you must import the OS module, and run its os.remove() function:
File name : index.py
import os
if os.path.exists("mahira.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
Delete Folder
To delete an entire folder, use the os.rmdir() method:
File name : index.py
import os
os.rmdir("myfolder")
File name : index.py