Python File Handling
Reading and writing data to files using Python is pretty straightforward. To do this, you must first open files in the appropriate mode.File handling is an important part of any web application.
To start with file handling you have to open file. To open file open() "open(filename, mode) "is used.
Mainly Three modes are used:
1."r",r opens the file in read only mode.
2."w",opens the file in write mode,create a file if not exist.
3."a", opens the file for appending,create a file if not exist.
Python File Methods
Function | Explanation |
---|
open() | To open a file |
close() | Close an open file |
fileno() | Returns an integer number of the file |
read(n) | Reads ‘n’ characters from the file till end of the file |
readable() | Returns true if the file is readable |
readline() | Read and return one line from the file |
readlines() | Reads and returns all the lines from the file |
seek(offset) | Change the cursor position by bytes as specified by the offset |
seekable() | Returns true if the file supports random access |
tell() | Returns the current file location |
writable() | Returns true if the file is writable |
write() | Writes a string of data to the file |
writelines() | Writes a list of data to the file |
Example (Reading Files)
f=open("text.txt",'r')
print(f.read(5)) # read only five characters
f.close() # close an open file
f=open("text.txt",'r')
for i in f:
print(i)
Output
GOedh
GOedhub technologies providing training in data science.
and also in ML and AI.
Example (To write data to file )
f=open("text.txt",'w')
f.write ("GOedhub technologies providing training in data science")
f.close()
Note:- write mode first remove all existing data from file and then write data to the file.
Example (To append data to the file )
f=open("text.txt",'a')
f.write ("Also in ML and AI")
Note:-append new data to the file without disturbing existing data.
Getting a directory listing
To get a list of all the files and folders in a particular directory in the filesystem, use os.listdir() in legacy versions of Python or os.scandir() in Python 3.x. os.scandir() is the preferred method to use if you also want to get file and directory properties such as file size and modification date.
os.listdir()- Returns a list of all files and folders in a directory
Example
import os
l=os.listdir("C:\\Users\\apex\\Downloads") #path for directory
for i in l:
print(i)
Note:- display all the folders, and files in downloads
os.scandir()- Returns an iterator of all the objects in a directory including file attribute information
Example
import os
l=os.scandir("C:\\Users\\apex\\Desktop\\python")
for i in l:
print(i)
Output
<DirEntry 'Ex_81.py'>
<DirEntry 'Ex_82.py'>
<DirEntry 'Pandas.docx'>
<DirEntry 'python'>
Note:- pathlib.Path.iterdir()- Returns an iterator of all the objects in a directory including file attribute information
List all files in a directory using scandir()
Example
basepath = 'Goeduhub _directory'
os.scandir(basepath) as entries:
for i in entries:
if i.is_file():
print(i.name)
Output
file1.py
file3.txt
file2.csv
Note:-All files display
List all subdirectories using scandir()
Example
basepath = 'Goeduhub_directory'
os.scandir(basepath) as entries:
for entry in entries:
if entry.is_dir():
print(entry.name)
Output
sub_dir_c
sub_dir_b
Note:- Display all the directories and sub-directories.
Making Directories
os.mkdir()-Creates a single subdirectory
os.makedirs()-Creates multiple directories, including intermediate directories
Example
import os
os.mkdir("Goeduhub_directory")
Note:- It will create a sub directory with name "Goeduhub_directory"
Python Tutorial
Machine Learning Tutorial
AI Tutorial
Free Online Tutorials