⬅ Previous Topic
Handling File ExceptionsNext Topic ⮕
First-Class Functions in Programming⬅ Previous Topic
Handling File ExceptionsNext Topic ⮕
First-Class Functions in ProgrammingFile paths are the directions your program follows to access files and folders stored in a computer's file system. Without a correct file path, your program won't be able to open or save data properly.
Let's say you have a file named data.txt
inside a folder called files
.
// Absolute path example
filePath = "/Users/username/Documents/project/files/data.txt"
// Relative path example (assuming current directory is 'project')
filePath = "files/data.txt"
Accessing file at /Users/username/Documents/project/files/data.txt Accessing file at files/data.txt
Question: When should I use a relative path?
Answer: Use a relative path when your files are part of your project structure and you want your code to be portable across machines.
Question: When is an absolute path more appropriate?
Answer: Use an absolute path when accessing a file stored in a fixed location outside your project folder.
You can use special path symbols to move around in the directory structure:
// Going up one level
filePath = "../config/settings.ini"
// Going down into a folder
filePath = "assets/images/logo.png"
Accessing settings.ini from parent directory Accessing logo.png from assets/images
Instead of manually adding slashes, it's safer to use path joining functions to build paths dynamically:
basePath = "data"
filename = "input.txt"
fullPath = joinPath(basePath, filename)
print(fullPath)
data/input.txt
Question: Why use joinPath()
instead of string concatenation?
Answer: joinPath()
handles the correct separators (like '/' or '\') for the operating system automatically, making your code portable.
..
to move up directories, and folder names to move down.⬅ Previous Topic
Handling File ExceptionsNext Topic ⮕
First-Class Functions in ProgrammingYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.