Expt 5
Expt 5
1
# Function to append data to a file
def append_to_file(filename, data):
with open(filename, 'a') as file: # Open the file in append mode
file.write(data + '\n') # Write the data followed by a newline
# Main function
def main():
filename = 'example.txt' # Specify the filename
OUTPUT:
5.2
# Function to count lines, words, and characters in a file
def count_file_contents(filename):
try:
with open(filename, 'r') as file: # Open the file in read mode
lines = file.readlines() # Read all lines in the file
line_count = len(lines) # Count the number of lines
word_count = 0 # Initialize word count
char_count = 0 # Initialize character count
for line in lines:
words = line.split() # Split the line into words
word_count += len(words) # Count words in the line
char_count += len(line) # Count characters in the line
# Main function
def main():
filename = 'example.txt' # Specify the filename
# Count lines, words, and characters
line_count, word_count, char_count = count_file_contents(filename)
# Main function
def main():
list_files_in_directory() # Call the function to list files