Monday, July 13, 2020

Python File Handling :Absolute and Relative Path usage,Different OS function Like chdir,mkdir,


Pyhton absolute path name and relative path name
In [1]:
fp=open('D:\\fd.txt','w')  #absolute path name ,new file fd.txt will create in D drive
fp.close()
In [5]:
fp=open('D:\\filc.txt','w') #absolute path name ,new file filc.txt will create in D drive
fp.close()
In [7]:
f=open('.\\filw.txt','w') #relative path name ,new file filw.txt will create in current working Directory 
In [9]:
import os
print(os.getcwd())
C:\Users\Acer
In [12]:
f=open('D:\\rks\\filrks.txt','w')  #new File filrks.txt will create in rks folder in D drive 
f.close()
In [13]:
f=open('.\\desktop\\fildesk.txt','w') # new file fildesk.txt created in desktop folder of current directory
f.close()
In [3]:
f=open('.\\desktop\\fildesk.xls','w')# new file fildesk.txt created in desktop folder of current directory
f.writelines([1,2,3])
f.close()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-bca88ebc9684> in <module>
      1 f=open('.\\desktop\\fildesk.xls','w')# new file fildesk.txt created in desktop folder of current directory
----> 2 f.writelines([1,2,3])
      3 f.close()

TypeError: write() argument must be str, not int
In [4]:
import os
print(os.getcwd())
C:\Users\Acer
In [8]:
os.chdir("D:") 
  
print("Directory changed") 
Directory changed
In [9]:
os.chdir("C:") 
  
print("Directory changed")
Directory changed
In [10]:
print(os.getcwd())
C:\
In [11]:
os.mkdir('binf')
In [15]:
os.mkdir('C:\\binf1')
---------------------------------------------------------------------------
FileExistsError                           Traceback (most recent call last)
<ipython-input-15-6d70ed4395c5> in <module>
----> 1 os.mkdir('C:\\binf1')

FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'C:\\binf1'
In [17]:
os.mkdir('D:\\binf2')
In [19]:
print(os.getcwd())
C:\
In [20]:
os.mkdir('D:\\binf2\\binf22')
In [21]:
print(os.getcwd())
C:\
In [22]:
os.chdir("C:\\binf") 
In [23]:
print(os.getcwd())
C:\binf
In [30]:
f=open('filecs.txt','w')
f.close()
In [32]:
print(os.getcwd())
C:\binf
In [36]:
isExist = os.path.exists('C:') 
print(isExist) 
True
In [38]:
isExist = os.path.exists('C:\\binf') 
print(isExist)
True
In [40]:
try :
    if(os.path.exists('C:\\fold')==False:
        os.mkdir('c:\\fold')
except:
    print('path exist already')
  File "<ipython-input-40-9c689c8e4257>", line 2
    if(os.path.exists('C:\\fold')==False:
                                        ^
SyntaxError: invalid syntax
In [ ]:
 

No comments:

Post a Comment