Python File Handling with Absolute Path
In some cases, you may need to use an absolute path to open or save a file in a specific location outside your script’s directory. In the example below, we use an absolute path pointing to the trymeyourself/karthickag04
folder.
Note: Ensure that the directory exists, otherwise Python will raise an error.
Example: Using an Absolute Path
# Using an absolute path to read a file
absolute_path = "C:/trymeyourself/karthickag04/example.txt"
# Writing to the file at the absolute path
with open(absolute_path, 'w') as file:
file.write('This file is saved in the absolute path folder.')
# Reading from the file at the absolute path
with open(absolute_path, 'r') as file:
content = file.read()
print(content)
Output
This file is saved in the absolute path folder.
Explanation: In this example, we specified the absolute path C:/trymeyourself/karthickag04/example.txt
to write and read the file. The with
statement ensures that the file is automatically closed after the operation.