Python : Working With File and Directory

Q: How to list all files From a directory ?
Ans : You Can do it any many way ,  mentioned  are  some way

1st way:
import os 
for file in os.listdir("C:/ra"):    
   if file.endswith(".gz"):        
    print(os.path.join("C:/ra", file))

# 2nd way:
import glob,os
os.chdir("C:/ra")
for file in glob.glob("*.gz"):    
print(file)

# 3rd way:
import os
for root, dirs, files in os.walk("C:/ra"):    
 for file in files:        
 if file.endswith(".gz"):            
   print(os.path.join(root, file))


Q: How to unzip  gz file into normal .
Ans :
import shutil
with open('C:/xyz.xml', 'rb') as f_in, gzip.open('C:/xyz.xml.gz', 'wb') as f_out:    
     shutil.copyfileobj(f_in, f_out)

Comments

Popular posts from this blog

Install Mysql from ZIP without MySQL Installer or Exe

Logging in Python .

Dictionary in Python