0% found this document useful (0 votes)
4 views2 pages

File Read

This document serves as a basic guide to Markdown formatting, covering headings, lists, emphasis, links, images, and code blocks. It includes examples of functions for reading file content and displaying lines from a text file, along with error handling for file operations. The document emphasizes the importance of file I/O operations and provides practical code snippets for implementation.

Uploaded by

copeyic220
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

File Read

This document serves as a basic guide to Markdown formatting, covering headings, lists, emphasis, links, images, and code blocks. It includes examples of functions for reading file content and displaying lines from a text file, along with error handling for file operations. The document emphasizes the importance of file I/O operations and provides practical code snippets for implementation.

Uploaded by

copeyic220
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Welcome to Markdown!

This is a basic example to help you get started with Markdown formatting.

Headings
Use # for headings. Add more # for smaller headings:

# creates the largest heading


## creates a medium heading
### creates a smaller heading

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}")

if name == "main": file_to_read = "sample.txt" # Assuming a file named 'sample.txt' exists

# Create a sample file for testing


try:
with open(file_to_read, 'w') as f:
f.write("This is the first line.\n")
f.write("This is the second line.\n")
f.write("This is the third line.\n")
for i in range(5):
f.write(f"This is line number {i+4}.\n")
f.write("This is the last line.\n")
except IOError as e:
print(f"Error creating sample file: {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)

You might also like