Tuesday, March 11, 2025

Easy python question - file based - 1

Python File Operations

Python File Operations

Check if a File Exists

import os def check_file_exists(filepath): if os.path.exists(filepath): print("File exists") else: print("File does not exist") # Example usage check_file_exists("/etc/passwd")

Clarification: Should the function handle different file types (e.g., regular files, directories, symlinks)? Should it handle potential exceptions like permission errors?

List All Files in the Current Directory

import os def list_files(): for filename in os.listdir("."): # "." represents the current directory print(filename) list_files()

Clarification: Should the script include hidden files? Should it recursively list files in subdirectories?

Get the Size of a File

import os def get_file_size(filepath): return os.path.getsize(filepath) # Example usage size = get_file_size("/etc/hosts") print(f"File size: {size} bytes")

Clarification: How should the function handle cases where the file doesn't exist or is inaccessible?

Read the First 10 Lines of a File

def read_first_lines(filepath, n=10): try: with open(filepath, 'r') as f: for i in range(n): line = f.readline().strip() #strip removes newline char if not line: # Check for end of file break print(line) except FileNotFoundError: print("File not found.") # Example usage read_first_lines("/etc/passwd")

Clarification: How should the function handle very large files efficiently? What should happen if the file has fewer than 10 lines?

Create an Empty File

def create_empty_file(filename): try: with open(filename, 'x') as f: # 'x' mode creates a new file and raises an error if it exists pass # No need to write anything for an empty file print(f"File '{filename}' created successfully.") except FileExistsError: print(f"File '{filename}' already exists.") create_empty_file("my_file.txt")

Clarification: What should happen if the file already exists?

No comments:

Post a Comment