0% found this document useful (0 votes)
8 views3 pages

Py 9

Uploaded by

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

Py 9

Uploaded by

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

SBL Python Experiment 9 Program to explore files and directories

Code:

# Program to explore files and directories

import os

def menu():
print("\n///MENU///")
print("1. To read content of one file and write it to another file")
print("2. To append data at the end of existing file")
print("3. To count number of lines, words and characters in a file")
print("4. To display files in current directory")
print("5. Exit")
return int(input("\nEnter your choice: "))

c=0
while c != 5:
c = menu()
if c == 1:
fname1 = input("\nEnter the file name of first file: ")
fname2 = input("\nEnter the file name of second file: ")
with open(fname1 + ".txt", "r") as f1, open(fname2 + ".txt", "w+") as f2:
s = f1.read()
f2.write(s)
f2.seek(0, 0)
s = f2.read()
print("\nThe contents of second file are:-\n")
print(s)
elif c == 2:
fname = input("\nEnter the file name: ")
with open(fname + ".txt", "a+") as f:
s = input("\nEnter the string to append:\n")
f.write(s)
f.seek(0, 0)
s = f.read()
print("\nThe contents of the updated file are:-\n")
print(s)
elif c == 3:
c=l=w=0
fname = input("\nEnter the file name: ")
with open(fname + ".txt", "r") as f:
for x in f:
words = x.split()
l += 1
w += len(words)
c += len(x)
print("\nNo. of lines = ", l)
print("\nNo. of words = ", w)
print("\nNo. of characters = ", c)
elif c == 4:
print("\nThe files in current directory are:-\n")
for root, dirs, files in os.walk('.'):
for file in files:
print(file)
elif c != 5:
print("\nIncorrect choice")
else:
print("\nExiting...")

OUTPUT:

3. To count number of lines, words and characters in a file


4. To display files in current directory

You might also like