Last active
November 18, 2023 16:40
-
-
Save mridulgain/0ae4ac0507352824b2abbec74025cd72 to your computer and use it in GitHub Desktop.
text file operations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def write_to_text_file(filename, data): | |
with open(filename, 'w') as file: | |
# Write a single line | |
file.write("Header: Name, Age, City\n") | |
# Write multiple lines | |
for line in data: | |
file.write(','.join(map(str, line)) + '\n') | |
print(f"Data written to {filename}.") | |
def append_to_text_file(filename, new_data): | |
with open(filename, 'a') as file: | |
# Append a single line | |
file.write(','.join(map(str, new_data)) + '\n') | |
print(f"Data appended to {filename}.") | |
def read_from_text_file(filename): | |
try: | |
with open(filename, 'r') as file: | |
# Read the entire file | |
content = file.read() | |
print("File Content:\n", content) | |
# Move the file cursor to the beginning | |
file.seek(0) | |
# Read one line at a time | |
line = file.readline() | |
print("First Line:", line) | |
# Move the file cursor to the beginning | |
file.seek(0) | |
# Read all lines into a list | |
lines = file.readlines() | |
print("All Lines as List:") | |
for line in lines: | |
print(line.strip()) # strip() removes leading and trailing whitespaces | |
# Get the current position of the file cursor | |
position = file.tell() | |
print("Current Position:", position) | |
except FileNotFoundError: | |
print(f"{filename} not found.") | |
except Exception as e: | |
print(f"Error reading {filename}: {e}") | |
# Example usage: | |
filename = "example_text_file.txt" | |
data_to_write = [ | |
["John", 30, "New York"], | |
["Alice", 25, "San Francisco"], | |
["Bob", 35, "Los Angeles"] | |
] | |
# Write to a text file | |
write_to_text_file(filename, data_to_write) | |
# Append to a text file | |
new_data_to_append = ["Charlie", 40, "Chicago"] | |
append_to_text_file(filename, new_data_to_append) | |
# Read from a text file | |
read_from_text_file(filename) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment