Skip to content

Instantly share code, notes, and snippets.

@iwconfig
Created April 18, 2025 20:56
Show Gist options
  • Save iwconfig/b6ee497bd60f1a3618dc19f298e167b1 to your computer and use it in GitHub Desktop.
Save iwconfig/b6ee497bd60f1a3618dc19f298e167b1 to your computer and use it in GitHub Desktop.
A simple utility for quickly scaffolding files without having to manually create directory structures or files beforehand. It lets you paste text where the very first line (a # comment) specifies the file path. It then writes the rest of the text into that file, automatically creating any necessary directories.
import os
def main():
print("Paste your text (end with an EOF signal: Ctrl-D on Unix/Mac, Ctrl-Z then Enter on Windows):")
try:
# Read multiline text from standard input until EOF
input_text = []
while True:
line = input()
input_text.append(line)
except EOFError:
pass
# Join all lines into one text block
full_text = "\n".join(input_text)
# Split the text into lines
lines = full_text.splitlines()
if not lines:
print("No text was provided!")
return
# The first line should be a comment containing the file path
first_line = lines[0].strip()
if not first_line.startswith("#"):
print("Invalid format: The first line should be a comment starting with '#' that contains the relative path.")
return
# Extract file path from the comment, skipping the '#' character and any extra whitespace.
relative_path = first_line[1:].strip()
if not relative_path:
print("File path not found in the first line!")
return
# The content to write starts after the first line.
file_content = "\n".join(lines[1:])
# Create directories if necessary
directory = os.path.dirname(relative_path)
if directory:
os.makedirs(directory, exist_ok=True)
# Write the file content to the file
try:
with open(relative_path, "w", encoding="utf-8") as f:
f.write(file_content + '\n')
print(f"File written successfully to '{relative_path}'.")
except Exception as e:
print(f"An error occurred while writing the file: {e}")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment