with open('/content/drive/My Drive/your-dataset.txt', 'r') as file: data = file.read()
Here's the rewritten program to read a text file using the specified file path:
def read_text_file(file_path):
try:
with open(file_path, 'r') as file:
data = file.read()
print(data)
except FileNotFoundError:
print("File not found.")
except IOError:
print("Error reading the file.")
# Example usage:
file_path = '/content/drive/My Drive/your-dataset.txt'
read_text_file(file_path)
In this version, the `open()` function is used with the specified file path `'/content/drive/My Drive/your-dataset.txt'`. The `with` statement ensures that the file is properly closed after reading its contents.
Make sure to replace `'your-dataset.txt'` with the actual file name and the `/content/drive/My Drive/` part with the correct path to your file. When you run the program, it will read the contents of the file and print them to the console.
Here's a Python program that adds the specified content to an existing text file:
def append_text_to_file(file_path, text):
try:
with open(file_path, 'a') as file:
file.write(text)
print("Content added to the file successfully.")
except FileNotFoundError:
print("File not found.")
except IOError:
print("Error writing to the file.")
# Example usage:
file_path = '/content/drive/My Drive/your-dataset.txt'
text_to_add = "The quick brown fox jumped over the lazy dog."
append_text_to_file(file_path, text_to_add)
In this program, the open() function is used with the file path in 'a' mode, which stands for "append" mode. This mode allows the program to open the file for writing and add content to the end of the file without overwriting its existing contents.
Make sure to replace '/content/drive/My Drive/your-dataset.txt' with the actual file path and 'The quick brown fox jumped over the lazy dog.' with the desired text you want to add to the file. When you run the program, it will append the specified text to the existing content of the file.