1. Write to FileProblem StatementWrite a program that creates a file called 'output.txt' and writes "Hello, File!" to it.ApproachUse open() with mode 'w' for writing. Don't forget to close the file or use 'with' statement.Solutionwith open('output.txt', 'w') as file: file.write("Hello, File!") print("File created successfully")
2. Read from FileProblem StatementRead and print the contents of a file called 'input.txt'.ApproachUse open() with mode 'r' for reading. Use read() method to get all content.Solutionwith open('input.txt', 'r') as file: content = file.read() print(content)
3. Read LinesProblem StatementRead a file line by line and print each line with its line number.ApproachUse readlines() or iterate over the file object. Use enumerate() for line numbers.Solution`with open('input.txt', 'r') as file: for i, line in enumerate(file, 1): print(f"Line {i
4. Append to FileProblem StatementAppend the text "New line" to an existing file called 'log.txt'.ApproachUse mode 'a' for appending. This adds content without overwriting existing data.Solutionwith open('log.txt', 'a') as file: file.write("New line\n") print("Text appended successfully")
5. Count Lines in FileProblem StatementWrite a function that counts the number of lines in a file.ApproachRead all lines using readlines() and return the length of the list.Solutiondef count_lines(filename): with open(filename, 'r') as file: return len(file.readlines()) print(count_lines('input.txt'))
6. Count Words in FileProblem StatementWrite a function that counts the total number of words in a file.ApproachRead the file, split each line into words, and count them.Solutiondef count_words(filename): with open(filename, 'r') as file: content = file.read() words = content.split() return len(words) print(count_words('input.txt'))
7. Copy FileProblem StatementWrite a function to copy the contents of one file to another.ApproachRead from source file and write to destination file.Solutiondef copy_file(source, destination): with open(source, 'r') as src: content = src.read() with open(destination, 'w') as dest: dest.write(content) copy_file('source.txt', 'destination.txt')
8. File Exists CheckProblem StatementWrite a function to check if a file exists before trying to read it.ApproachUse os.path.exists() or handle FileNotFoundError with try-except.Solutionimport os def file_exists(filename): return os.path.exists(filename) if file_exists('test.txt'): print("File exists") else: print("File not found")
9. Write List to FileProblem StatementWrite a list of strings to a file, with each string on a new line.ApproachIterate through the list and write each item with a newline character.Solutiondata = ["Apple", "Banana", "Cherry"] with open('fruits.txt', 'w') as file: for item in data: file.write(item + '\n')
10. Read File into ListProblem StatementRead a file and store each line as an element in a list (without newline characters).ApproachUse readlines() and strip() to remove newline characters.Solutionwith open('input.txt', 'r') as file: lines = [line.strip() for line in file.readlines()] print(lines)
11. Search in FileProblem StatementWrite a function to search for a specific word in a file and return the line numbers where it appears.ApproachIterate through lines with enumerate(), check if the word is in each line.Solutiondef search_word(filename, word): line_numbers = [] with open(filename, 'r') as file: for i, line in enumerate(file, 1): if word in line: line_numbers.append(i) return line_numbers print(search_word('input.txt', 'Python'))
12. Replace Text in FileProblem StatementReplace all occurrences of a word in a file with another word.ApproachRead the file, use replace() method, then write back to the file.Solutiondef replace_text(filename, old_word, new_word): with open(filename, 'r') as file: content = file.read() content = content.replace(old_word, new_word) with open(filename, 'w') as file: file.write(content) replace_text('input.txt', 'old', 'new')
13. Write CSV DataProblem StatementWrite a list of dictionaries to a CSV file with headers.ApproachUse the csv module. Create a DictWriter with fieldnames and write rows.Solution`import csv data = [ {'name': 'Alice', 'age': 25
14. Read CSV DataProblem StatementRead a CSV file and print each row as a dictionary.ApproachUse csv.DictReader to read CSV as dictionaries.Solutionimport csv with open('people.csv', 'r') as file: reader = csv.DictReader(file) for row in reader: print(row)
15. Write JSON DataProblem StatementWrite a Python dictionary to a JSON file.ApproachUse json.dump() to write dictionary to file.Solution`import json data = { 'name': 'Alice', 'age': 25, 'city': 'New York'
16. Read JSON DataProblem StatementRead a JSON file and print its contents as a Python dictionary.ApproachUse json.load() to read JSON file into a dictionary.Solutionimport json with open('data.json', 'r') as file: data = json.load(file) print(data)
17. Merge Multiple FilesProblem StatementMerge the contents of multiple text files into a single output file.ApproachRead each file and append its content to the output file.Solutiondef merge_files(file_list, output_file): with open(output_file, 'w') as outfile: for filename in file_list: with open(filename, 'r') as infile: outfile.write(infile.read()) outfile.write('\n') merge_files(['file1.txt', 'file2.txt'], 'merged.txt')
18. File SizeProblem StatementWrite a function to get the size of a file in bytes.ApproachUse os.path.getsize() to get file size.Solution`import os def get_file_size(filename): return os.path.getsize(filename) print(f"File size: {get_file_size('input.txt')
19. Delete FileProblem StatementWrite a function to safely delete a file if it exists.ApproachCheck if file exists using os.path.exists(), then use os.remove().Solution`import os def delete_file(filename): if os.path.exists(filename): os.remove(filename) print(f"{filename
20. List Files in DirectoryProblem StatementWrite a function to list all files in a directory with a specific extension.ApproachUse os.listdir() to get all files, then filter by extension using endswith().Solutionimport os def list_files_by_extension(directory, extension): files = [] for filename in os.listdir(directory): if filename.endswith(extension): files.append(filename) return files print(list_files_by_extension('.', '.txt'))