Part of the series

Several example codes

~2 min read • Updated Sep 27, 2025

Program Overview

This Python program reads a text file containing multiple file paths with optional query strings.
It separates each path from its query and displays both parts clearly on the screen.
This is useful for parsing URLs, file references, or structured input formats.


Sample Input File Structure:

Assume the file contains lines like:
D:/Data/file1.txt?version=2
D:/Docs/report.pdf?user=admin


Python Code:


# Path to the input file
file_path = "D:/Data/files.txt"

# Read lines from the file
with open(file_path, "r", encoding="utf-8") as f:
    lines = f.readlines()

# Process each line to separate path and query
for line in lines:
    line = line.strip()
    if "?" in line:
        path, query = line.split("?", 1)
    else:
        path, query = line, "(No query string)"
    
    print("File Path:", path)
    print("Query:", query)
    print("---")

Sample Output:


File Path: D:/Data/file1.txt  
Query: version=2  
---  
File Path: D:/Docs/report.pdf  
Query: user=admin  
---

Explanation:

- The file is opened using open() in read mode
- Each line is stripped of whitespace using strip()
- If a ? is present, the line is split into path and query using split()
- If no query exists, a default message is shown
- The results are printed with clear labels for readability


Written & researched by Dr. Shahin Siami