File Read
File Read
This is a basic example to help you get started with Markdown formatting.
Headings
Use # for headings. Add more # for smaller headings:
Lists
Unordered List
Item 1
Item 2
Sub-item 2.1
Sub-item 2.2
Ordered List
1. First item
2. Second item
3. Third item
Emphasis
Bold text: **Bold**
Italic text: *Italic*
Strikethrough: ~~Strikethrough~~
Links
Click here to visit Google
Images
Code Blocks
Inline code: Use `backticks` for inline code
Block of code:
def read_file_content(filepath): """ Reads the content of a text file and returns it as a string.
What: This function takes the path to a file (string) as input and attempts to open
and read its entire content. It includes error handling for file not found
and other potential I/O errors.
Theory: File I/O (Input/Output) operations are essential for interacting with files
on the system. The `open()` function is used to open a file in a specific mode
('r' for reading in this case). The `with` statement is used to ensure that
the file is automatically closed even if errors occur. The `.read()` method
reads the entire content of the file into a single string. Error handling using
`try...except` blocks is crucial for robust file operations, allowing the program
to gracefully handle situations where the file might not exist or cannot be accessed.
"""
try:
with open(filepath, 'r') as file:
content = file.read()
return content
except FileNotFoundError:
return f"Error: File not found at '{filepath}'"
except IOError as e:
return f"Error reading file '{filepath}': {e}"
def display_file_lines(filepath, max_lines=10): """ Reads and displays the first 'max_lines' of a text file.
What: This function takes a file path and an optional maximum number of lines to display.
It opens the file and prints each line up to the specified limit.
Theory: Instead of reading the entire file at once, iterating through the file object line
by line is more memory-efficient, especially for large files. The `for line in file:`
construct allows processing each line individually. The `strip()` method is often
used to remove leading and trailing whitespace (including newline characters) from
each line before printing. Limiting the number of lines displayed can be useful
for previewing file content.
"""
try:
with open(filepath, 'r') as file:
print(f"\n--- First {max_lines} lines of '{filepath}' ---")
for i, line in enumerate(file):
if i < max_lines:
print(line.strip())
else:
print("...")
break
print("---------------------------------------------")
except FileNotFoundError:
print(f"Error: File not found at '{filepath}'")
except IOError as e:
print(f"Error reading file '{filepath}': {e}")
content = read_file_content(file_to_read)
if isinstance(content, str) and content.startswith("Error"):
print(content)
else:
print("\n--- File Content ---")
print(content)
print("--------------------")
display_file_lines(file_to_read, 5)