File Handling Python
File Handling Python
os.listdir(r"C:\Users\ritemukherjee\Desktop\p9\python_toc\python\day1")
4)
>Want to create a directory
os.mkdir('test2024')
5)
>By mistake create the same directory in a specific path
os.mkdir('test2024')
>will throw some error,"fileexists"
6)
>Delete directory
os.rmdir('test2024')
7)
>Check the current path and put the directory in the given path
print(os.getcwd()) # check the older path
os.chdir('test2024') # change the directory path to 2024
print(os.getcwd()) # after changing the current path will be showing.
8)
>We could not able to delete the directory if it contains child directory
os.rmdir(r'C:\Users\ritemukherjee\Desktop\p9\python_toc\python') #As it contains
child directory
>>throw some error w(permission)
9)
>If we are not sure about that, whether the directory is created or not.
that time if we want to create the directory
if not os.path.exists('test2024'):
os.mkdir('test2024')
print('Folder created successfully')
else:
print('Already exists..!!')
10)
>If you want to check whether the file is there in a path or not.
os.path.isfile('test')
>can check the same process for other file as well
11)
>If you want to check whether the directory is there in a path or not.
os.path.isdir('test')
12)
>if u want to fetch some files based on some specific condition
16)
f = open('sample.txt', 'r')
data = f.read()
f.close()
print(data)
print(type(data))
17)
>read file data in single line separated by comma
f = open('sample.txt', 'r')
data = f.readlines()
f.close()
print(data)
print(type(data))