Working with
File Paths



Understanding File Paths

File 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.

Types of File Paths

Example 1: Absolute vs Relative Path

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"

Output:

Accessing file at /Users/username/Documents/project/files/data.txt
Accessing file at files/data.txt

How to Decide Between Relative and Absolute Paths?

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.

Example 2: Navigating Up and Down the Directory Tree

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"

Output:

Accessing settings.ini from parent directory
Accessing logo.png from assets/images

Example 3: Path Joining for Cross-Platform Compatibility

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)

Output:

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.

Points to Remember



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

Mention your name, and programguru.org in the message. Your name shall be displayed in the sponsers list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M