String and File Handling Exercises
String and File Handling Exercises
To implement a Caesar cipher encryption for any printable characters, consider the following steps: 1. Input the plaintext and the distance value for the cipher shift. 2. Iterate through each character in the plaintext. 3. For each character, check if it is printable by using the `string.printable` character set. 4. Determine the index of the character within the `string.printable` set, apply the shift (using modulo to wrap around if necessary), and replace the character with the new shifted character based on the new index. 5. Assemble the encrypted characters into a single string. Here is a Python code snippet illustrating these steps: ```python import string plaintext = "Hello World!" distance = 3 printable_chars = string.printable result = "" for char in plaintext: if char in printable_chars: old_index = printable_chars.index(char) new_index = (old_index + distance) % len(printable_chars) result += printable_chars[new_index] else: result += char print("Encrypted:", result) ``` This approach ensures the cipher works with all printable ASCII characters and handles overflow using modular arithmetic.
To create a file comparison script in Python for identifying the first differing line between two text files, follow these steps: 1. Prompt the user for the names of the two files to be compared. 2. Open both files for reading. 3. Use a loop to read and compare lines from both files simultaneously. 4. If a pair of lines differ, print "No", along with the differing lines, and break the loop. 5. If the end of the file is reached without finding a difference, print "Yes". Here's an illustrative example in Python: ```python def compare_files(file1, file2): with open(file1, 'r') as f1, open(file2, 'r') as f2: for line1, line2 in zip(f1, f2): if line1 != line2: print("No") print(f"File1: {line1}") print(f"File2: {line2}") return print("Yes") # Usage compare_files('file1.txt', 'file2.txt') ``` This script will efficiently identify the first line that differs between the two files using a zip to pair lines from both files.
To develop a Python script that can both encrypt and decrypt a text using a Caesar cipher with the same key, design functions for encryption and decryption that shift characters forward or backward by the specified distance value. Utilize the `string.printable` set for character manipulation. 1. Define a function for encryption that shifts characters forward by the distance key. 2. Define a decryption function that shifts characters backward by the same distance key. 3. Use the modulo operation to ensure the shift stays within bounds of the character set index. Here is a sample implementation: ```python import string def caesar_cipher(text, distance, mode='encrypt'): printable_chars = string.printable transformed = '' for char in text: if char in printable_chars: idx = printable_chars.index(char) if mode == 'encrypt': new_idx = (idx + distance) % len(printable_chars) else: new_idx = (idx - distance) % len(printable_chars) transformed += printable_chars[new_idx] else: transformed += char return transformed text = "Sample Text" distance = 3 encrypted_text = caesar_cipher(text, distance, mode='encrypt') decrypted_text = caesar_cipher(encrypted_text, distance, mode='decrypt') print("Encrypted:", encrypted_text) print("Decrypted:", decrypted_text) ``` This method assures reversibility of ciphering with the same key, maintaining flexibility for both operations.
The strategy to write a Python script to copy the contents of one file into another while ensuring the target file is overwritten involves: 1. Prompt the user for the names of the source and target files. 2. Open the source file in read mode and the target file in write mode. 3. Read the entire contents from the source and write them to the target file. 4. Handle any exceptions like FileNotFoundError for the source file. Here's a Python script implementing these steps: ```python source_file = input("Enter the source filename: ") target_file = input("Enter the target filename: ") try: with open(source_file, 'r') as sf, open(target_file, 'w') as tf: content = sf.read() tf.write(content) print("File copied successfully.") except FileNotFoundError: print(f"Error: The file {source_file} was not found.") ``` This ensures that the destination file is overwritten with the source content, effectively copying the data.
To calculate the average of integers stored in a text file where each integer is on a separate line, open the file for reading, iterate through each line, convert the line to an integer, and accumulate them to calculate the sum and count the number of integers. Finally, divide the sum by the count to obtain the average. Here is a code example: ```python with open('integers.txt', 'r') as f: total = 0 count = 0 for line in f: total += int(line.strip()) count += 1 average = total / count print("Average:", average) ``` This approach ensures each line is processed as an integer, while maintaining a running total and count to calculate the average efficiently.
Evaluating the effectiveness of a Python program that interacts with the user to enter a filename and outputs lines in reverse order involves checking: 1. **Correctness**: Test with various file sizes and content types to verify the program reads all lines correctly and reverses them accurately. 2. **Robustness**: Evaluate the handling of errors such as file non-existence, permission issues, and empty files. 3. **Efficiency**: Analyze performance using large files to ensure it executes within reasonable time and memory limits. 4. **Usability**: Consider user interaction quality; verify clear prompts for filenames and meaningful error messages. 5. **Security**: Assess how the program handles unexpected input and whether it prevents code injections or path traversal. Below is a basic structure and considerations: ```python filename = input("Enter filename: ") try: with open(filename, 'r') as file: lines = file.readlines() for line in reversed(lines): print(line.rstrip()) except FileNotFoundError: print("Error: File not found.") except PermissionError: print("Error: Permission denied.") ``` The program should have test cases for each evaluation criteria with documented outcomes for improvement and assurance against system environment variations.
To design a Python script that reads a filename and prints its contents or an error message if the file does not exist: 1. Prompt the user to enter the filename. 2. Use a try-except block to attempt opening the file. 3. If the file opens successfully, read and print the contents. 4. If a `FileNotFoundError` is raised, print an error message. Here is an example of the implementation in Python: ```python filename = input("Enter the filename: ") try: with open(filename, 'r') as file: contents = file.read() print(contents) except FileNotFoundError: print(f"Error: {filename} not found.") ``` This method ensures robust handling of file presence and provides feedback to the user if the specified file does not exist.
To implement a Python script that lists all the items in the current working directory, use the `os` module that provides a portable way of using operating system dependent functionality: 1. Import the `os` module. 2. Use `os.listdir()` to retrieve the list of entries in the directory given by `os.getcwd()`. 3. Print each item returned by `os.listdir()`. Here's a Python example: ```python import os print("Items in current directory:") for item in os.listdir(os.getcwd()): print(item) ``` The script uses the current working directory as specified by `os.getcwd()` and lists its contents with `os.listdir()`, which is efficient for directory management tasks.
To write a Python script that reads file content, numbers each line, and saves the result into a new file, perform the following steps: 1. Ask the user for input and output file names. 2. Read the input file line by line. 3. Write each line to the output file, prepending a line number with right-justified four-column formatting. Here's a Python implementation: ```python input_file = input("Enter the input filename: ") output_file = input("Enter the output filename: ") with open(input_file, 'r') as infile, open(output_file, 'w') as outfile: line_number = 1 for line in infile: numbered_line = f"{line_number:4} > {line}" outfile.write(numbered_line) line_number += 1 print("Lines have been numbered and written to", output_file) ``` This script reads each line, formats it with a line number right-justified over four spaces, and writes to the output file, preserving the order and contents of the original data.