Trying to make the user write to a file and seeing if it exists and if they should override it

    print("Enter a file name to save your database to.")
    name = input('Enter name of text file: ')+'.txt'
    if name print ("Would you like to overwrite this file? Yes or No")
    if "yes"

Dani AI

Generated

asked how to prompt for a filename and decide whether to overwrite; clarified the language, and provided a helpful exists-check example. The short, more robust pattern below uses Path and exclusive-creation mode so the existence check and file creation are atomic (avoids a time-of-check / time-of-use race). The snippet is for Python 3 and keeps handling simple and clear.

from pathlib import Path
import sys

name = input("Enter name of text file: ").strip()
if not name:
    sys.exit("Empty filename")

p = Path(name).expanduser()
if p.suffix == "":
    p = p.with_suffix(".txt")

try:
    # create only if missing
    with p.open("x", encoding="utf-8") as fh:
        fh.write("...")  # place DB output here
except FileExistsError:
    ans = input("{} exists. Overwrite? [y/N]: ".format(p)).strip().lower()
    if ans in ("y", "yes"):
        with p.open("w", encoding="utf-8") as fh:
            fh.write("...")
    else:
        sys.exit("Abort: not overwriting")

Notes and tips: using mode "x" (raises FileExistsError) is preferable to calling exists() before open because it prevents race conditions; falling back to "w" only after explicit consent preserves behavior. expanduser() and with_suffix() normalize common inputs (tilde and missing .txt). Handle PermissionError and other OSErrors around the open/write in real code. For safer replacement of large or critical files, write to a temporary file and atomically rename (os.replace) to avoid partial writes. For appending use mode "a". This approach builds on 's check-for-file idea but makes the create-or-fail step atomic and simpler to reason about.

Recommended Answers

All 3 Replies

What language are you using? What code have you tried?

I'm using Python

You can start with this

import os

print('Enter a file name to save your database to.')
name = input('Enter name of text file: ').strip()
if name:
    name = os.path.expanduser(name + '.txt')
    if os.path.isfile(name):
        while True:
            overwrite = input("Would you like to overwrite this file? Yes or No: ")
            overwrite = overwrite.strip().capitalize()
            if overwrite in ('Yes', 'No'):
                break
            else:
                print('Error: please answer Yes or No')
        if overwrite == 'No':
            raise NotImplementedError("I don't know what to do!")
else:
    raise RuntimeError('Got an empty name')
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.