#!/usr/bin/env python # coding: utf-8 # # Reading and Writing files # In[1]: f = open("file-demo-read.txt", "r") data = f.read() print(data) f.close() # # More clean way. The close method will be implicitly called just before exiting with block. # In[2]: with open("file-demo-read.txt", "r") as f: data = f.read() print(data) # # Reading one line at a time # In[3]: with open("file-demo-read.txt", "r") as f: data = f.readline() print(data) # # Writing into file # In[4]: f = open("file-demo-write.txt", "r+") f.write("This is a sample text.") f.close() # ### Reading the written content # In[5]: f = open("file-demo-write.txt", "r") data = f.read() print(data) f.close() # # File positioning # In[6]: f = open("file-demo-write.txt", "r") f.seek(5) data = f.readline() print(data) f.seek(0) data = f.readline() print(data) f.close() # # File system operations # In[7]: import os # ### Create a directory # In[8]: os.mkdir("demo") # ### Rename a directory # In[9]: os.rename("demo", "demo-dir") # ### Change current working directory # In[10]: curr_dir_backup = os.getcwd() os.chdir("demo-dir") # ### Print current working directory # In[11]: curr_dir = os.getcwd() print(curr_dir) # ### Create a file under this directory # In[12]: f= open("demo.txt","w+") f.close() # ### Rename this file # In[13]: os.rename("demo.txt", "demo-file.txt") # ### Create two directory under this directory # In[14]: os.mkdir("demo-sub-dir-1") os.mkdir("demo-sub-dir-2") # ### List all files and directories # In[15]: dir_list = os.listdir() print(dir_list) # ### Get the statistics of a director. Current directory in the case below. # In[16]: stat = os.stat(".") print(stat) # ## Clean up # In[17]: if(os.path.exists("../demo-dir")): if(os.path.exists("demo-sub-dir-1")): os.rmdir("demo-sub-dir-1") if(os.path.exists("demo-sub-dir-2")): os.rmdir("demo-sub-dir-2") if(os.path.isfile("demo-file.txt")): os.remove("demo-file.txt") os.rmdir("../demo-dir") os.chdir(curr_dir_backup)