0% found this document useful (0 votes)
5 views

File Handling Python

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

File Handling Python

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

1)

>check the current path


import os
os.getcwd()
2)
>To check the files and folder list
os.listdir()
3)
>To check the files and folder list in a specific path

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')

check same for other directory

12)
>if u want to fetch some files based on some specific condition

for file in os.listdir():


if file.startswith('0'):
print(file)
13)
f = open('sample.txt', 'r') # error,coz need to open in write mode
14)
f = open('sample.txt', 'w')
f.write('This is sample text: line 1')
15
>Append word or sentence
f = open('sample.txt', 'a')
f.write('\nThis is sample text: line 3')
f.close()

16)

>Read file data

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))

You might also like